[英]How to determine which View executed a command
我有一個名為 InformationView.xaml 的視圖,這個視圖被重新用於顯示來自 3 個不同來源的相同信息(每個視圖都有不同的 window 標題)。 每個 View 的數據上下文都設置了一個 ViewModel 類型的相同實例。 在我的 ViewModel class 中,我有一個 ICommand 屬性,視圖中的“關閉”按鈕綁定到該屬性。 -- 有沒有辦法確定誰是命令的發送者? (具體來說,由 window 標題)。
這是一個例子:
我有一個帶有以下按鈕的視圖 class(“注意:每個視圖都有不同的 window 標題/顯示來自不同來源的數據——但使用相同的視圖)
<Button Width="75" Height="23" Margin="0,0,5,5" Content="Close" Command="{Binding CloseCommand}" />
我有一個 ViewModel class 使用以下命令
public ICommand CloseCommand
{
get
{
if (this._closeCommand == null)
{
this._closeCommand = new RelayCommand(Command => this.OnClose());
}
return _closeCommand;
}
}
我正在尋找一種方法來確定哪個 window 執行了命令(我將有多個使用相同 ViewModel 的 View 實例)。
我不確定我是否理解正確。 但是,您可以實現Unloaded
事件。 在該事件方法中設置斷點,並在您遇到斷點時設置斷點。 您可以檢查該視圖的 window 標題屬性。
只是將Close()
方法設為 public 以便其他對象可以指定關閉行為應該是什么?
您的InformationViewModel
中與此類似的內容:
public event EventHandler RequestClose;
void OnRequestClose()
{
EventHandler handler = this.RequestClose;
if (handler != null)
handler(this, EventArgs.Empty);
}
然后您可以在其他視圖模型中使用它,如下所示:
InformationViewModel.Close += CloseMethod;
public CloseMethod(object sender, EventArgs e)
{
// Implement close logic here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.