Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

combobox - WPF Visibility of a UI element based on combo selection

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...