WPF 解决 Style.Trigger 中数据绑定失效的问题

参考:stackoverflow

问题背景

有如下代码,发现在 ImageSource="{Binding SomeImage}" 中没有绑定的当前的 DataContext

xaml 复制代码
<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>

解决办法

改成如下即可

xaml 复制代码
<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>
相关推荐
△曉風殘月〆5 小时前
如何在WPF中捕获窗口外的事件
wpf
爱吃烤鸡翅的酸菜鱼1 天前
Java 事件发布-订阅机制全解析:从原生实现到主流中间件
java·中间件·wpf·事件·发布订阅
武藤一雄2 天前
WPF中ViewModel之间的5种通讯方式
开发语言·前端·microsoft·c#·wpf
CSharp精选营3 天前
都是微软亲儿子,WPF凭啥干不掉WinForm?这3个场景说明白了
c#·wpf·跨平台·winform
baivfhpwxf20233 天前
wpf TextBlock 控件如何根据内容换行?
wpf
亘元有量-流量变现3 天前
鸿蒙、安卓、苹果音频设备技术深度解析与开发实践
android·wpf·harmonyos·亘元有量·积分墙
软泡芙3 天前
【Bug】ReactiveUI WPF绑定中依赖属性不更新的问题分析与解决方案
java·bug·wpf
浪扼飞舟3 天前
WPF输入验证(ValidationRule)
java·javascript·wpf
IOFsmLtzR4 天前
Flink Agents 源码解读 --- (5) --- ActionExecutionOperator
microsoft·flink·wpf
廋到被风吹走5 天前
【AI】Codex 复杂任务拆解:从“一气呵成“到“步步为营“
人工智能·wpf