A ComboBox
和Button
位於不同的用戶控件上,並且彼此不會看到。儘管如此,它們都綁定到相同的ViewModel
。如何通過在WPF中綁定來執行方法
Button
有一個Click事件,它在其用戶控件的代碼隱藏中執行一個方法。
我希望能夠在更改ComboBox
時執行此方法。例如,假設ComboBox
的SelectedItem
綁定到ViewModel
中的一個屬性,現在當它被更改時,我希望執行其他控件中的方法。
A ComboBox
和Button
位於不同的用戶控件上,並且彼此不會看到。儘管如此,它們都綁定到相同的ViewModel
。如何通過在WPF中綁定來執行方法
Button
有一個Click事件,它在其用戶控件的代碼隱藏中執行一個方法。
我希望能夠在更改ComboBox
時執行此方法。例如,假設ComboBox
的SelectedItem
綁定到ViewModel
中的一個屬性,現在當它被更改時,我希望執行其他控件中的方法。
您希望創建引發屬性更改的對象(即SelectedComboBoxItem)。然後使用生成的事件來啓動您嘗試創建的事件觸發器。
您提到這兩個控件不知道彼此,但綁定到相同ViewModel
。我發現在屬性更改時執行某種類型代碼的最簡單方法是直接從set { }
訪問修飾符執行它。考慮以下幾點:
public class MyViewModel
{
private MyObject _currentObject;
public MyObject CurrentObject
{
get { return this._currentObject; }
set
{
this._currentObject = value;
//Usually where OnPropertyChanged goes or however you implement INotifyPropertyChanged
//Where we call our command, logic can be introduced if needed.
//Also we may just call the method directly.
this.SomeCommand.Execute(null);
}
}
private Command _someCommand;
public Command SomeCommand
{
get
{
return this._someCommand ?? (this._someCommand = new Command(
() =>
{
this.SomeMethod();
},
() =>
{
//The CanExecute test, returns bool.
return this._currentObject != null ? true : false;
}));
}
}
private string SomeMethod()
{
return "I just got called yo!";
}
}
更新:
由於執行代碼中存在處理程序,你將不得不做一些工作,得到這個權利。儘管這違反MVVM校長它將工作:
ViewModel
的新方法下,我們堅持與SomeMethod()
名。您需要獲取對處理程序中ViewModel
的引用。我假設這已被設置爲DataContext
MyViewModel viewModel = DataContext as MyViewModel;
接下來,您將需要調用從處理程序方法:
viewModel.SomeMethod();
現在你可以調用從方法您的財產的set { }
部分包含在ViewModel
之內。
我希望這對你有效。
感謝您的洞察力,但我的問題是,我試圖調用的方法是在用戶控件的代碼隱藏中持有'Button'。也許這是因爲我的設計糟糕,這種情況已經發生。點擊時,我正在使用該按鈕更新繪圖。我也想在更換組合框時做到這一點。 – Vahid