WPF Routed Commands and ShowDialog Windows

喜你入骨 提交于 2019-12-21 06:17:58

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/359304/wpf-routed-commands-and-showdialog-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!