By default, you must implement INotifyPropertyChanged in your ViewModel:
public class MainWindowViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged;
Then add NotifyPropertyChanged () to your property installer.
Ok Then add a new property with the background color of the grid in the ViewModel:
private Brush _gridBackground; public Brush GridBackground { get { return _gridBackground; } set { _gridBackground = value; NotifyPropertyChanged(); } }
And bind the grid background to your property:
<Grid Background="{Binding GridBackground}">
Finally, you can simply change the GridBackground in the command handler:
public void ChangeBgColor(object obj) { GridBackground = Brushes.Blue; }
You must remember that it is bad practice to add WPF classes, such as Brush, to your code. It is best to use IValueConverter in the XAML code and BCL classes in your ViewModel. For example, you can use the enumeration in the ViewModel and convert it to a brush in the ValueConverter.
Add a new enumeration for the ViewModel property:
public enum GridState { Valid, Invalid }
Change property type:
private GridState _gridBackground; public GridState GridBackground { get { return _gridBackground; } set { _gridBackground = value; NotifyPropertyChanged(); } }
Add new class with value converter
public class GridStateToBackgroundColorConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { GridState val = (GridState) value; if(val == GridState.Valid) return Brushes.Green; return Brushes.Red; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotSupportedException(); } #endregion }
Add a new static resource to your control
<UserControl.Resources> <converters:GridStateToBackgroundColorConverter x:Key="gridStateToBackgroundColorConverter" /> </UserControl.Resources>
Update binding to your property
<Grid Background="{Binding GridBackground, Converter={StaticResource gridStateToBackgroundColorConverter}">
source share