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

UWP中如何根据Item属性隐藏ListView项?RelativeSource怎么设置

UWP中ListViewItem根据ItemModel属性隐藏项的正确实现

你不需要复杂的RelativeSource设置,UWP里可以通过两种简单方式实现需求:

方式一:直接绑定ItemModel的IsAvailable属性

ListViewItem的DataContext默认就是ItemsCollection中的ItemModel实例,因此可以直接绑定目标属性:

<ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
        <interactivity:Interaction.Behaviors>
            <core:DataTriggerBehavior
                Binding="{Binding IsAvailable, Mode=OneWay}"
                Value="False">
                <core:ChangePropertyAction
                    PropertyName="Visibility"
                    Value="Collapsed" />
            </core:DataTriggerBehavior>
        </interactivity:Interaction.Behaviors>
    </Style>
</ListView.ItemContainerStyle>

方式二:使用RelativeSource Self绑定Content属性

如果你坚持通过ListViewItem的Content属性访问ItemModel,UWP的RelativeSource仅支持Self模式,设置如下即可:

<ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
        <interactivity:Interaction.Behaviors>
            <core:DataTriggerBehavior
                Binding="{Binding RelativeSource={RelativeSource Self}, Path=Content.IsAvailable, Mode=OneWay}"
                Value="False">
                <core:ChangePropertyAction
                    PropertyName="Visibility"
                    Value="Collapsed" />
            </core:DataTriggerBehavior>
        </interactivity:Interaction.Behaviors>
    </Style>
</ListView.ItemContainerStyle>

关键说明

和WPF不同,UWP的RelativeSource仅提供Self这一种模式(没有FindAncestor等选项),所以需要访问当前控件自身属性时,用RelativeSource={RelativeSource Self}即可。而ListViewItem的Content属性默认指向绑定的ItemModel对象,因此两种方式都能正常工作。

另外要确保已引用Microsoft.Xaml.Behaviors.Uwp.Managed NuGet包,否则interactivity和core命名空间无法识别。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 14:38:11