You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在设置自定义DataContext的UserControl中绑定ItemsControl当前项属性

方案1:使用RelativeSource获取父级上下文

ItemsControl每个项的容器ContentPresenter的DataContext默认就是列表的当前项,不会受你给Icon设置自定义DataContext的影响,直接修改DataTrigger的绑定表达式即可:

<DataTrigger Binding="{Binding DataContext.Status, RelativeSource={RelativeSource AncestorType=ContentPresenter}}" Value="Default">
    <Setter Property="Background" Value="Red" />
</DataTrigger>

这里的RelativeSource会向上查找可视化树中最近的ContentPresenter元素,取它的DataContext(也就是你要的ListOfItems当前项),再访问其Status属性。

方案2:通过Tag属性中转绑定

如果担心可视化树结构变动导致RelativeSource查找失效,可以用控件的Tag属性作为中转,提前把当前列表项绑定到Icon的Tag上:

<local:Icon Width="18" Height="18" Tag="{Binding}">
    <local:Icon.Style>
        <Style TargetType="local:Icon">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Tag.Status, RelativeSource={RelativeSource Self}}" Value="Default">
                    <Setter Property="Background" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </local:Icon.Style>
</local:Icon>

Tag="{Binding}"会直接把当前DataTemplate的上下文(列表当前项)绑定到Icon的Tag属性,之后在Trigger里直接读取自身Tag的Status属性即可。

内容的提问来源于stack exchange,提问作者Joery

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 06:48:01