[英]Defining a general Style with a DataTrigger in ResourceDictionary but specify the DataTrigger binding path in the view
I want to define a general look and feel of a control in a ResourceDictionary
using a style with a DataTrigger
.我想使用带有
DataTrigger
的样式在ResourceDictionary
定义控件的一般外观。
Is it possible to specify the DataTrigger
binding path in the view?是否可以在视图中指定
DataTrigger
绑定路径? 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.我必须将(在这种情况下)我的
Rectangle
的DataContext
绑定到我想要的属性。 Then I have to bind the trigger in my style to the DataContext
.然后我必须以我的风格将触发器绑定到
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!我希望它可以帮助某人!
如果您不想使用 DataContext,您可以使用附加属性并绑定到它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.