Sunday, March 6, 2011

WPF Routed Commands and ShowDialog Windows

Hello,

I was wondering how a window opened through ShowDialog is treated in the Visual Tree.

For example, Window A opens Window B through a ShowDialog. When firing a routed command on Window B, Window A does not receieve the command (even though it is listening for it).

Is there any way to make this work?

Thanks! Jon

From stackoverflow
  • We run into this situation all the time in our application. We use the Window.Owner property and ICommandSource.CommandTarget property for this.

    For example, in Window A:

    DialogWindow windowB = new DialogWindow();
    windowB.Owner = this;
    windowB.ShowDialog();
    

    Then, in DialogWindow, all the controls that execute commands have their CommandTarget bound to the parent Window's Owner:

    <Window x:Class="DialogWindow" x:Name="wnd">
        <Button Command="SomeCommand" CommandTarget="{Binding Owner, ElementName=wnd}"/>
    </Window>
    

    Or alternatively, if you're executing from code inside Window B:

    SomeCommand.Execute(params, this.Owner);
    

    CommandTarget will let Window A listen for CanExecute and Execute.

0 comments:

Post a Comment