ComboBox
和Button
位于不同的用户控件上,彼此之间没有看到。但它们都绑定到相同的ViewModel
。
Button
有一个Click事件,它在其用户控件的代码隐藏中执行一个方法。
我希望在更改ComboBox
时能够执行此方法。例如,假设SelectedItem
的{{1}}绑定到ComboBox
中的属性,现在当它被更改时,我希望执行另一个控件中的方法。
答案 0 :(得分:1)
您提到这两个控件彼此不知道,但是绑定到同一个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
部分调用该方法。
我希望这适合你。
答案 1 :(得分:0)
你想要创建一个引发属性改变的对象(即SelectedComboBoxItem)。然后使用生成的事件来启动您尝试创建的事件触发器。