I would like to change the color of my Label
in the view based on a type in my ViewModel. For ex:
My class in ViewModel has a bool
property like following:
MyViewModel
{
public bool IsBlueColor {get; set;} //Here I will raise the `PropertyChanged`
}
How can I wrap a trigger for this value to update Foreground
property of my label. All I could figure out was changing the property of UI element based on its on property using DataTrigger
. But not based on viewmodel.
How can I achieve this in xaml?
Right now I am doing this:
<Label.Style>
<Style TargetType="Label" BasedOn="{StaticResource LabelStyle}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsBlueColor, RelativeSource={RelativeSource AncestorType={x:Type local2:MyViewModel}}}" Value="True">
<Setter Property="Foreground" Value="RoyalBlue"/>
</DataTrigger>
<DataTrigger Binding="{Binding Path=IsBlueColor, RelativeSource={RelativeSource AncestorType={x:Type local2:MyViewModel}}}" Value="False">
<Setter Property="Foreground" Value="White"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Label.Style>
Change the style triggers to:
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsBlueColor}" Value="True">
<Setter Property="Foreground" Value="RoyalBlue"/>
</DataTrigger>
<DataTrigger Binding="{Binding Path=IsBlueColor}" Value="False">
<Setter Property="Foreground" Value="White"/>
</DataTrigger>
</Style.Triggers>
Check implementation of INotifyPropertyChanged in ViewModel.
this works in a sample for me.
Sample :
class LabelViewModel:INPC
{
public event PropertyChangedEventHandler PropertyChanged=new delegate{};
bool _isBlueColor;
public bool IsBlueColor
{
get
{
return _isBlueColor;
}
set
{
_isBlueColor=value;
OnPropertyChange();
}
}
public OnPropertyChange([CallerMemberName] string propname="")
{
PropertyChanged.Invoke(this,ew PropertyChangedEventArgs(propname));
}
}
Create an instance of LabelViewModel(labelVM) & assign to label1.DataContext=labelVM;