【发布时间】:2017-10-30 19:21:04
【问题描述】:
根据我下面的代码,我希望能够在单击Button 1 时更改Button 2 的背景颜色。
XAML 文件
<Grid>
<Button x:Name="Button1"
Content="Button 1"
Command="{Binding Button1Command}"/>
<Button x:Name="Button2"
Content="Button 2"/>
</Grid>
视图模型文件
public class MyViewModel : ViewModelBase
{
public ICommand Button1Command{get;private set;}
public MyViewModel(){
Button1Command = new RelayCommand(() => button1_Click());
}
private void button1_Click()
{
Console.WriteLine("Button 1 clicked");
// how can I change the background color of Button 2 here
this.Dispatcher.Invoke(() => {
Button2.Background = Brushes.Red;
});
}
}
【问题讨论】:
-
只需将事件处理程序放在代码后面并在那里更改颜色。按钮和它们的背景完全是视图概念——你不必以任何方式让你的模型参与这样的事情。现在,如果这些不仅是颜色,而且例如它们代表按钮状态(例如,一种颜色是“忙碌”或“禁用”)-那就不同了。但是使用视图模型(甚至像一个答案所暗示的那样使用信使)只是在点击时更改按钮颜色完全是矫枉过正,没有多大意义。
-
@Evk 颜色将根据 viewModel 中发生的某些情况来回更改。
标签: c# wpf mvvm mvvm-light