1

How can I set window's owner to Application.Current.MainWindow through XAML? So far I've tried this:

<Window x:Class="ModalWindow.CustomModalWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Owner="System.Windows.Application.Current.MainWindow">
<!--Some XAML code-->
</Window>

That didn't work.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Mykhailo Seniutovych
  • 3,527
  • 4
  • 28
  • 50

1 Answers1

5

Owner="System.Windows.Application.Current.MainWindow" won't work because "System.Windows.Application.Current.MainWindow" is just a string

Window.Owner isn't a dependency property, so binding to static source ("{Binding Path=MainWindow, Source={x:Static Application.Current}}") won't work also

I modified App class like this:

namespace WpfDemos
{
    public partial class App : Application
    {
        public static Window CurrentMainWindow
        {
            get { return Current.MainWindow; }
        }
    }
}

and then in my window referenced that property via {x:Static} extension:

<Window x:Class="WpfDemos.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wpfDemos="clr-namespace:WpfDemos"
        Owner="{x:Static wpfDemos:App.CurrentMainWindow}"

so it is possible, but why?

ASh
  • 34,632
  • 9
  • 60
  • 82
  • Why so much work, when you just can add it to the code. see my answer https://stackoverflow.com/a/48004247/2289942 – Nawed Nabi Zada Dec 28 '17 at 08:46
  • I am creating a custom modal dialog window and would like to set its owner to MainWindow, I thought I would do it in XAML instead of the code behind so it would be more elegant, but seemingly there is no straightforward solution because I will have to modify `App.xaml.cs` in that case. – Mykhailo Seniutovych Dec 28 '17 at 13:22
  • `App` class is very often modified or extended to perform initialization when application is launched. Adding a property is also completely acceptable – ASh Dec 28 '17 at 13:33