WPF 解决 Style.Trigger 中数据绑定失效的问题
问题背景
有如下代码,发现在 ImageSource="{Binding SomeImage}"
中没有绑定的当前的 DataContext
<Grid>
<Border>
<Border.Style>
<Style TargetType="Border">
<Style.Triggers>
<DataTrigger Binding="{Binding SomeValue, ElementName=myControl, Mode=OneWay}" Value="0">
<Setter Property="Background">
<Setter.Value>
<!-- 此处 Binding 没有生效 -->
<ImageBrush ImageSource="{Binding SomeImage}" />
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
</Border>
</Grid>
解决办法
改成如下即可
<Grid>
<Grid.Resource>
<ImageBrush x:key="myImage" ImageSource="{Binding SomeImage}" />
<Style x:key="myStyle" TargetType="Border">
<Style.Triggers>
<DataTrigger Binding="{Binding SomeValue, ElementName=myControl, Mode=OneWay}" Value="0">
<Setter Property="Background" Value="{StaticResource myImage}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Grid.Resource>
<Border Style="{StaticResource myStyle}"/>
</Grid>