MVVM在单击时更改网格的背景颜色我是MVVM模式的真正初学者。我试图通过单击按钮来更改网格的背景。我有一个带有包含按钮的网格的xaml,以及一个我想在单击按钮时更改网格背景的ViewModel.cs。在我单击之前,MessageBox没有成功显示...publicICommandButtonCommand{get{返回m_ButtonCommand;}设置{m_ButtonCommand=值;}}publicMainWindowViewModel(){ButtonCommand=newRelayCommand(newAction(ChangeBgColor));}publicvoidChangeBgColor(objectobj){/*我想在这里更改网格颜色*/}}}抱歉我的英语不好。最好的祝愿。最合适的是,您应该在ViewModel中实现INotifyPropertyChanged:publicclassMainWindowViewModel:INotifyPropertyChanged{//此方法由每个属性的Set访问器调用。//应用于可选propertyName的CallerMemberName特性导致调用者的属性名称被替换为参数。privatevoidNotifyPropertyChanged([CallerMemberName]StringpropertyName=""){if(PropertyChanged!=null){PropertyChanged(this,newPropertyChangedEventArgs(propertyName));然后,将NotifyPropertyChanged()添加到属性设置器。好的。接下来,向ViewModel添加一个具有网格背景颜色的新属性:privateBrush_gridBackground;publicBrushGridBackground{get{return_gridBackground;}设置{_gridBackground=值;NotifyPropertyChanged();}}并将您的网格背景设置为您的属性:最后,您只需更改命令处理程序中的GridBackground:publicvoidChangeBgColor(objectobj){GridBackground=Brushes.Blue;您应该记住,将WPF类(如Brush)添加到您的代码中是一种不好的做法。更好的方法是在XAML代码中使用IValueConverter,在ViewModel中使用BCL类。例如,您可以在ViewModel中使用枚举并在ValueConverter中将其转换为画笔。为ViewModel的属性添加新枚举:publicenumGridState{Valid,Invalid}更改属性类型:privateGridState_gridBackground;publicGridStateGridBackground{get{return_gridBackground;}设置{_gridBackground=值;NotifyPropertyChanged();}}为值转换器添加新类publicclassGridStateToBackgroundColorConverter:IValueConverter{#regionIValueConverterMemberspublicobjectConvert(objectvalue,TypetargetType,objectparameter,System.Globalization.CultureInfoculture){GridStateval=(GridState)value;如果(val==GridState.Valid)返回Brushes.Green;返回Brushes.Red;}publicobjectConvertBack(objectvalue,TypetargetType,objectparameter,System.Globalization.CultureInfoculture){thrownewNotSupportedException();}#endregion}如果要更改网格背景颜色,请添加绑定到命令参数的新静态资源更新属性。您可以将任何UI控件作为Command参数传递。在您的情况下,传递网格以访问视图模型中的网格。为网格分配一个名称并将该名称用作命令参数。为此,您需要实现如下代码:对.xaml文件进行此更改后。使用传递的Grid实现参数化中继命令以在Viewmodel文件中使用。实现参数化中继命令尝试实现以下代码:privateICommandm_ButtonCommand;publicICommandButtonCommand{get{返回m_ButtonCommand;}设置{m_ButtonCommand=值;}}publicMainWindowViewModel(){ButtonCommand=newRelayCommand(ChangeBgColor);}publicvoidChangeBgColor(Gridgrid){if(grid!=null)grid.Background=Brushes.Red;//任何你想改变的颜色。我希望这会奏效。谢谢。以上就是C#学习教程:MVVM点击时改变grid的背景色。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场,如涉及侵权,请点击右边联系管理员删除。如需转载请注明出处:
