提问人:Stefan 提问时间:3/17/2017 最后编辑:Stefan 更新时间:10/20/2021 访问量:1715
在 ResourceDictionary 中使用 DataTrigger 定义 Style,但在视图中指定 DataTrigger 绑定路径
Defining a Style with a DataTrigger in ResourceDictionary but specify the DataTrigger binding path in the view
问:
我想使用带有 .ResourceDictionary
DataTrigger
是否可以在视图中指定绑定路径?
如果没有,有没有一些巧妙的替代方案来实现我的目标?DataTrigger
我的目标是重用图形定义(包括触发器),但每次使用触发器时都会将触发器链接到不同的数据源。
示例样式:
<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>
在视图中,我希望像这样使用这种风格:
<Rectangle Width="50" Height="50"
Style="{StaticResource LedBehavior}"
DataTriggerBindingPath="**PropertyInViewModel**"/>
谢谢!
答:
5赞
Stefan
3/20/2017
#1
解决方案看起来非常简洁,不太困难。
我必须将(在这种情况下)我的绑定到我想要的财产。然后,我必须将我的样式中的触发器绑定到 .DataContext
Rectangle
DataContext
下面的工作示例。
示例样式:
<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>
示例(部分)视图:
<Rectangle Width="50" Height="50"
Style="{StaticResource LedBehavior}"
DataContext="{Binding PropertyInViewModel}"/>
我希望它能帮助到某人!
1赞
Dennis
4/7/2017
#2
如果您不想使用 DataContext,则可以使用附加属性并绑定到此属性。
评论