[英]How to determine which View executed a command
I have a View called InformationView.xaml and this same View is re-used to display the same information from 3 different sources (each view has a different window title).我有一个名为 InformationView.xaml 的视图,这个视图被重新用于显示来自 3 个不同来源的相同信息(每个视图都有不同的 window 标题)。 Each View has their datacontext set the same instance of one ViewModel type.
每个 View 的数据上下文都设置了一个 ViewModel 类型的相同实例。 Within my ViewModel class, I have an ICommand property that the 'Close' button inside the View is bound to.
在我的 ViewModel class 中,我有一个 ICommand 属性,视图中的“关闭”按钮绑定到该属性。 -- Is there a way to determine who the sender was of the command?
-- 有没有办法确定谁是命令的发送者? (specifically, by window title).
(具体来说,由 window 标题)。
Here is an example:这是一个例子:
I have a view class with the following button ("Note: each View will have a different window title / display data from a different source--but the same View is used)我有一个带有以下按钮的视图 class(“注意:每个视图都有不同的 window 标题/显示来自不同来源的数据——但使用相同的视图)
<Button Width="75" Height="23" Margin="0,0,5,5" Content="Close" Command="{Binding CloseCommand}" />
I have a ViewModel class with the following command我有一个 ViewModel class 使用以下命令
public ICommand CloseCommand
{
get
{
if (this._closeCommand == null)
{
this._closeCommand = new RelayCommand(Command => this.OnClose());
}
return _closeCommand;
}
}
I am looking for a way to determine which window executed the command (I will have multiple instances of the View using the same ViewModel).我正在寻找一种方法来确定哪个 window 执行了命令(我将有多个使用相同 ViewModel 的 View 实例)。
I'm not sure if I understand you correctly.我不确定我是否理解正确。 However, you could possibly implement the
Unloaded
event.但是,您可以实现
Unloaded
事件。 Set a breakpoint inside that event method and when you hit the breakpoint.在该事件方法中设置断点,并在您遇到断点时设置断点。 You could check the window title property for that view.
您可以检查该视图的 window 标题属性。
What about just making the Close()
method public so that other objects can specify what the close behavior should be?只是将
Close()
方法设为 public 以便其他对象可以指定关闭行为应该是什么?
Something along the lines of this in your InformationViewModel
:您的
InformationViewModel
中与此类似的内容:
public event EventHandler RequestClose;
void OnRequestClose()
{
EventHandler handler = this.RequestClose;
if (handler != null)
handler(this, EventArgs.Empty);
}
Then you can use it from within your other view models like this:然后您可以在其他视图模型中使用它,如下所示:
InformationViewModel.Close += CloseMethod;
public CloseMethod(object sender, EventArgs e)
{
// Implement close logic here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.