Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Button Background color through MVVM pattern in WPF

Tags:

I am using MVVM light with WPF. I want to set button background color based on some specific condition through ViewModel. Kindly suggest some way to get it. Thanks

like image 348
Yogesh Avatar asked Sep 07 '11 06:09

Yogesh


2 Answers

You could bind the control's Background to a property on the viewmodel, the trick is to use an IValueConverter to return a Brush with the color you require. Here's an example that converts a boolean value from the viewmodel to a color:

public class BoolToBrushConverter : IValueConverter {     public object Convert(object value, Type targetType, object parameter, CultureInfo culture)     {         if (value == null)             return Brushes.Transparent;          return Convert.ToBoolean(value)             ? Brushes.Red             : Brushes.Transparent;      }      public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)     {         throw new NotImplementedException();     } } 

with a binding expression like

"{Binding Reviewed, Converter={StaticResource BoolToBrushConverter}}" 

where Reviewed is your boolean viewmodel property.

like image 78
almog.ori Avatar answered Sep 18 '22 12:09

almog.ori


Using triggers:

<Button>     <Button.Style>         <Style TargetType="Button">             <!-- Set the default value here (if any).                   If you set it directly on the button that will override the trigger. -->             <Setter Property="Background" Value="LightGreen" />             <Style.Triggers>                 <DataTrigger Binding="{Binding SomeConditionalProperty}"                              Value="True">                     <Setter Property="Background" Value="Pink" />                 </DataTrigger>             </Style.Triggers>         </Style>     </Button.Style> </Button> 

Explanation of the comment.


Using a dependent property in a view model (MVVM):

public bool SomeConditionalProperty  {     get { /*...*/ }     set     {         //...          OnPropertyChanged(nameof(SomeConditionalProperty));         //Because Background is dependent on this property.         OnPropertyChanged(nameof(Background));     } }  public Brush Background =>     SomeConditionalProperty ? Brushes.Pink : Brushes.LightGreen; 

Then you just bind to Background.

like image 35
H.B. Avatar answered Sep 16 '22 12:09

H.B.