Universal windows apps don't support data triggers.
Without data triggers, how can I change the background color of a button using xaml and data binding only when a boolean property in the view model changes?
For example given this XAML:
<StackPanel>
<Button Name="ButtonA" Click="ButtonA_Click" Content="A" />
<Button Name="ButtonB" Click="ButtonB_Click" Content="B" />
<Button Name="ButtonC" Click="ButtonC_Click" Content="C" />
</StackPanel>
with this code behind
private void ButtonA_Click(object sender, RoutedEventArgs e)
{
Model.IsOnA = !Model.IsOnA;
}
private void ButtonB_Click(object sender, RoutedEventArgs e)
{
Model.IsOnB = !Model.IsOnB;
}
private void ButtonC_Click(object sender, RoutedEventArgs e)
{
Model.IsOnC = !Model.IsOnC;
}
What is the best approach to change the background color of the buttons using data binding when the corresponding property in the view model is changed?
I was able to make it work for one button only using the VisualStateManager manager:
<VisualStateManager.VisualStateGroups>
<VisualStateGroup>
<VisualState>
<VisualState.StateTriggers>
<StateTrigger IsActive="{x:Bind Model.IsOnA, Mode=OneWay}" />
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Target="ButtonA.Background" Value="Red"></Setter>
<Setter Target="ButtonA.Foreground" Value="White"></Setter>
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
But with multiple buttons that bind to different properties in the view model this approach is not working.
An alternative to converters are attached properties. Useful if more than one property should be changed or if one needs access to the view model (through the DataContext of the control) to decide how to change the user interface properties.
Here is a simple example:
It can be used like this in XAML:
You can check my previous answer in the following link. Delete button on ListView items
You just need to create a converter which converts Boolean to SolidColorBrush. For example:
And to add it to your Xaml Binding.
Hope this helps.
One could put a property with the background color brush directly into the view model.
For example in the view model:
and in XAML: