Example #1
0
        private static Window EnsureWindow(object viewModel, object view, bool asChildWindow, bool asDialog)
        {
            var window = view as Window;
            if (window == null)
            {
                window = new Window
                {
                    Content = view ?? viewModel,
                    SizeToContent = SizeToContent.WidthAndHeight,
                };
                window.Loaded += (sender, e) => window.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

                if (asDialog)
                {
                    window.ResizeMode = ResizeMode.NoResize;

                    // According to Windows Style Guides: Model dialog should not have system menu.
                    WindowsHelper.SetShowIcon(window, false);
                }
            }

            var hasDisplayName = viewModel as IDisplayName;
            if (hasDisplayName != null
                && window.ReadLocalValue(Window.TitleProperty) == DependencyProperty.UnsetValue // No local value.
                && BindingOperations.GetBinding(window, Window.TitleProperty) == null)          // No binding.
            {
                // Bind Window.Title to ViewModel.DisplayName.
                var binding = new Binding("DisplayName");
                window.SetBinding(Window.TitleProperty, binding);
            }

            var owner = InferOwnerOf(window);
            if (owner != null && asChildWindow)
            {
                window.ShowInTaskbar = false;
                window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                window.Owner = owner;
            }
            else
            {
                window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            }

            var hasDialogResult = viewModel as IDialogResult;
            if (asDialog && hasDialogResult != null)
            {
                var behaviors = Interaction.GetBehaviors(window);
                if (!behaviors.OfType<DialogResultBehavior>().Any())
                {
                    // Bind Window.DialogResult to viewModel.DialogResult using a behavior.
                    var dialogResultBehavior = new DialogResultBehavior();
                    var binding = new Binding("DialogResult") { Mode = BindingMode.TwoWay };
                    BindingOperations.SetBinding(dialogResultBehavior, DialogResultBehavior.DialogResultProperty, binding);
                    behaviors.Add(dialogResultBehavior);
                }
            }

            return window;
        }