【问题标题】:WPF Visibility of a UI element based on combo selection基于组合选择的 UI 元素的 WPF 可见性
【发布时间】:2011-02-03 10:41:30
【问题描述】:

仅在选择组合中的某个项目时尝试显示标签。代码应该几乎可以解释它。

    <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>

【问题讨论】:

    标签: wpf combobox visibility


    【解决方案1】:

    这里有两个问题。首先,应在样式中指定默认可见性。但即便如此,它也不会起作用,因为触发器上的绑定正在比较 SelectedValue、ComboBoxItem 对象和字符串对象,并且永远不会等价。为了使示例简单,我在 ComboBoxItem 的 Tag 属性中放置了适当的值。尽管比较的实际实现可能会根据应用的具体需求而有所不同。

        <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>
    

    【讨论】:

    • 顺便说一句:有没有办法在多个控件中重用这个触发器而不重复它?我有多个要隐藏/基于此选择的控件。它们是单独的网格单元,所以我不能只隐藏整个堆栈面板。
    • 如果您的意思是跨多种控件类型(标签、按钮等),我会使用附加的行为来做到这一点。如果您的意思是在同一控件类型的不同实例之间重用,您应该将样式设置为资源。
    • 附加行为。谢谢斯科特,你太棒了。
    【解决方案2】:

    “更清洁”的解决方案是

    <ComboBox>
        <ComboBoxItem x:Name="iOne" Content="One"/>
        <ComboBoxItem x:Name="iTwo" Content="Two"/>
        <ComboBoxItem x:Name="iThree" Content="Three"/>
    </ComboBox>
    
    <Label Content="One is shown">
     <Label.Style>
        <Style TargetType="Label">
            <Setter Property="Visibility" Value="Hidden" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=iOne, Path=IsSelected}"    Value="True">
                    <Setter Property="Visibility"  Value="Visible"/>
                </DataTrigger> 
            </Style.Triggers>
        </Style>
     </Label.Style>
    </Label>
    

    【讨论】:

    • 我在 WPF 中找不到组合框的 IsSelected 属性。
    • 它是 ComboBoxItem @ShantanuGupta 上的一个属性
    猜你喜欢
    • 2021-05-07
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多