I want to define a general look and feel of a control in a ResourceDictionary
using a style with a DataTrigger
.
Is it possible to specify the DataTrigger
binding path in the view?
If not, is there some neat alternative to reach my goal?
My goal is to reuse the graphical definition (including triggers) but link the trigger to a different data source each time I use it.
Example style:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style TargetType="Rectangle" x:Key="LedBehavior">
<Setter Property="Fill" Value="LightGray"/>
<Style.Triggers>
<DataTrigger Binding="{Binding **DefineThisPathInTheView**}" Value="True">
<Setter Property="Fill" Value="DarkGreen"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ResourceDictionary>
In the view I hope to use this style somewhat like this:
<Rectangle Width="50" Height="50"
Style="{StaticResource LedBehavior}"
DataTriggerBindingPath="**PropertyInViewModel**"/>
Thank you!
The solution appears very neat and not too difficult.
I have to bind the DataContext
of (in this case) my Rectangle
to the property I want. Then I have to bind the trigger in my style to the DataContext
.
The working example below.
Example style:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style TargetType="Rectangle" x:Key="LedBehavior">
<Setter Property="Fill" Value="LightGray"/>
<Style.Triggers>
<DataTrigger Binding="{Binding}" Value="True">
<Setter Property="Fill" Value="DarkGreen"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ResourceDictionary>
Example (part of) view:
<Rectangle Width="50" Height="50"
Style="{StaticResource LedBehavior}"
DataContext="{Binding PropertyInViewModel}"/>
I hope it helps someone!