Hello Screens Sample Dialogs XAML Added at Runtime

Topics: Getting Started, UI Architecture
Feb 26, 2013 at 5:39 PM
I used part of the Hello Screens Sample in my project to implement modal dialogs. I have a base class for a screen and added code to insert the "Dialogs" into the screen XAML at runtime so that I dont' have to code it on each screen. By doing this I also can select other controls in the designer by clicking on them because the Dialogs control was always on the top. I thought other may benefit from this code so i though I would share it.
       public void AttachView(object view, object context)
            if (CacheViews)
                Views[context ?? View.DefaultContext] = view;

            var nonGeneratedView = View.GetFirstNonGeneratedView(view);

            var element = nonGeneratedView as FrameworkElement;
            if (element != null && !(bool)element.GetValue(PreviouslyAttachedProperty))
                element.SetValue(PreviouslyAttachedProperty, true);
                View.ExecuteOnLoad(element, (s, e) => OnViewLoaded(s));

                // Retrieve the root visual
                var rootVisual = VisualTreeHelper.GetChild((UserControl)view, 0);

                if (((FrameworkElement)rootVisual).FindName("Dialogs") == null)
                    // Add Dialogs child object to the root visual
                    if (rootVisual is Grid)
                        Grid layoutRoot = (Grid)rootVisual;
                        int columns = layoutRoot.ColumnDefinitions.Count;
                        int rows = layoutRoot.RowDefinitions.Count;

                        ContentControl dialogsContent = new ContentControl();
                        dialogsContent.Name = "Dialogs";
                        dialogsContent.VerticalContentAlignment = VerticalAlignment.Stretch;
                        dialogsContent.HorizontalContentAlignment = HorizontalAlignment.Stretch;

                        Grid.SetColumnSpan(dialogsContent, columns);
                        Grid.SetRowSpan(dialogsContent, rows);

                        Log.Warn("Root Object {0} is not a grid.  Cannot Add Dialogs Content.", rootVisual);

            OnViewAttached(nonGeneratedView, context);
            ViewAttached(this, new ViewAttachedEventArgs { View = nonGeneratedView, Context = context });