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>
相关推荐
△曉風殘月〆3 小时前
WPF中的变换(Transform)功能详解
wpf
mingupup3 小时前
为WPF应用增加项目图标
wpf
张人玉6 小时前
c#WPF基础知识
开发语言·c#·wpf
yantuguiguziPGJ15 小时前
WPF 联合 Web 开发调试流程梳理(基于 Microsoft.Web.WebView2)
前端·microsoft·wpf
Aevget15 小时前
DevExpress WPF中文教程:Data Grid - 如何使用虚拟源?(二)
.net·wpf·界面控件·devexpress·ui开发·数据网格
大美B端工场-B端系统美颜师21 小时前
工控软件开发选择难?Electron、Qt、WPF 对比
qt·electron·wpf
c#上位机1 天前
MefBootstrapper在Prism引导程序中的使用
c#·wpf·prism
没有bug.的程序员2 天前
服务治理与 API 网关:微服务流量管理的艺术
java·分布式·微服务·架构·wpf
Brianna Home2 天前
【案例实战】鸿蒙分布式调度:跨设备协同实战
华为·wpf·harmonyos
c#上位机3 天前
wpf中Grid的MouseDown 事件无法触发的原因
c#·wpf