A191919
A191919

Reputation: 3442

WPF binding visibility

I have label that shoul be visible when RadioButton First or Second IsChecked=true and Collapsed when Third or Fourth IsChecked=false. Is it only one way to do it pass name of the button to the converter and in converter decide should it be collapsed or visible?

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition></RowDefinition>
        <RowDefinition></RowDefinition>
    </Grid.RowDefinitions>
    <StackPanel Orientation="Vertical">
        <RadioButton Content="Visible" x:Name="First"></RadioButton>
        <RadioButton Content="Visible" x:Name="Second"></RadioButton>
        <RadioButton Content="Collapsed" x:Name="Third"/>
        <RadioButton Content="Collapsed" x:Name="Fourth"></RadioButton>
    </StackPanel>
    <Label Content="Test" Grid.Row="1"></Label>
</Grid>

Upvotes: 1

Views: 402

Answers (2)

James
James

Reputation: 113

I suggest using the MVVM pattern with a framework like MVVM Light. Then in the View Model, you can have a property for LabelVisiblity that the Label binds to.

If the MVVM pattern is not an option, you could add events handlers for each CheckBox's Checked event. Then set the Visility there.

    public MainWindow()
    {
        InitializeComponent();

        textBlock.Visibility = Visibility.Collapsed;

        option1.Checked += Option_Checked;
        option2.Checked += Option_Checked;
        option3.Checked += Option_Checked;
        option4.Checked += Option_Checked;
    }

    private void Option_Checked(object sender, RoutedEventArgs e)
    {
        var option = (sender as RadioButton);
        if (option.Name == "option1" || option.Name == "option2")
            textBlock.Visibility = Visibility.Collapsed;
        else
            textBlock.Visibility = Visibility.Visible;

    }

Upvotes: 0

tym32167
tym32167

Reputation: 4881

You can implement IMultiValueConverter and use it to bind Visibility to several values. You can find example here

Upvotes: 4

Related Questions