Home > front end >  How to use a xaml control to show/hide other controls?
How to use a xaml control to show/hide other controls?

Time:01-13

I have a combobox in xaml which presents the user with 1, 2 and 3 as options.

<ComboBox x:Name="cbNoOfChoices" Text="{Binding Path = NoOfChoices, Mode=OneWayToSource}" >
            <ComboBoxItem>1</ComboBoxItem>
            <ComboBoxItem>2</ComboBoxItem>
            <ComboBoxItem>3</ComboBoxItem>
    </ComboBox> 
        
    <Label x:Name="lblNo1" Content="Number 1" ></Label>
        <TextBox x:Name="txtbxNo1" Text="{Binding Path = No1, Mode=OneWayToSource}"/>

     <Label x:Name="lblNo2" Content="Number 2" ></Label>
        <TextBox x:Name="txtbxNo2" Text="{Binding Path = No2, Mode=OneWayToSource}"/>
   
     <Label x:Name="lblNo3" Content="Number 3" ></Label>
        <TextBox x:Name="txtbxNo3" Text="{Binding Path = No3, Mode=OneWayToSource}"/>

Two questions:

  1. If 0 is selected then only label "Number 1" with associated textbox must be visible. If 1 is selected then only label "Number 1" and label "Number 2" with associated textboxes must be visible, etc. How do I do this?

  2. Also have different equations being used depending on the combobox selection. Not sure how to extract the combobox selection to dictate which equation to use. Will a property by itself work?

public double NoOfChoices { get { return noOfChoices; }

        set
        {
            noOfChoices = value;
        }
    }

Will value above be the combobox selection?

Thanks.

CodePudding user response:

Q: "use a (..) control to show/hide other controls?"

This seems an anti-pattern. When you need to hide an edit control, set its Visibility property.

myEdit.Visibility = Visibility.Hidden;
                    // Visibility.Collapsed;
                    // Visibility.Visible;

You can do the same with its title label. When the components you want to hide are multiple, put them onto a panel container and hide the panel.

In WPF use observables, tags and bindings, ref these other SO questions,

Elegant way to change control visibility in wpf

Want to show/hide control from ViewModel in wpf

.. which refers to MSDN - How to: Implement Property Change Notification

CodePudding user response:

MVVM solution that I can think of would be:

  • Implement ValueConverter that converts an integer (or double) to Visibility and accepts a parameter value that when the converted value equals the parameter, returned value is Visibility.Visible and is Visibility.Collapsed in all other cases
  • For all your labels (lblNo1, lblNo2, etc.) bind their Visibility to your combobox SelectedIndex property with the earlier implemented value converter giving the respective parameter.

Let me know if it's clear to you. If not, I'll try to prepare some code.

  • Related