基于组合选择的 UI 元素的 WPF 可见性 [英] WPF Visibility of a UI element based on combo selection

查看:12
本文介绍了基于组合选择的 UI 元素的 WPF 可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试仅在选择组合中的某个项目时才显示标签.代码应该能很好地解释它.

Trying to show a label only when a certain item in a combo is selected. Code should pretty much explain it.

    <ComboBox Name="comboMyCombo">
        <ComboBoxItem>Don't show the label</ComboBoxItem>
        <ComboBoxItem>Show the label</ComboBoxItem>
    </ComboBox>

    <Label Visibility="Collapsed">This is my label
        <Label.Style>
            <Style>
                <Style.Triggers>
                    <DataTrigger 
                            Binding="{Binding ElementName=comboMyCombo, Path=SelectedValue}" Value="Show the label">
                        <Setter Property="Label.Visibility" Value="Visible"></Setter>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Label.Style>
    </Label>

推荐答案

这里有两个问题.首先应该在样式中指定默认可见性.但即使这样它也不会工作,因为触发器上的绑定正在比较 SelectedValue、ComboBoxItem 对象与字符串对象,并且永远不会等效.为了使示例保持简单,我在 ComboBoxItem 的 Tag 属性中放置了适当的值.尽管比较的实际实施可能会因应用的具体需求而异.

There are two issues here. First the default visibility should be specified in the style. But even with that it won't work because the binding on the trigger is comparing a SelectedValue, a ComboBoxItem object with a string object and that will never be equivalent. To keep the example simple, I've placed appropriate values in the ComboBoxItem's Tag properties. Although the actual implementation of the comparison will likely vary based on the specific needs of the app.

    <ComboBox Name="comboMyCombo">
        <ComboBoxItem Tag="Hide">Don't show the label</ComboBoxItem>
        <ComboBoxItem Tag="Show">Show the label</ComboBoxItem>
    </ComboBox>

    <Label>This is my label
        <Label.Style>
            <Style>
                <Setter Property="Label.Visibility" Value="Collapsed"></Setter>
                <Style.Triggers>
                    <DataTrigger  
                        Binding="{Binding ElementName=comboMyCombo, Path=SelectedItem.Tag}" Value="Show">
                        <Setter Property="Label.Visibility" Value="Visible"></Setter>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Label.Style>
    </Label>

这篇关于基于组合选择的 UI 元素的 WPF 可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆