Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding off Visibility of another element - and inverting

I'd like to make Control A visibile if Control B is hidden, and vice versa. Right now I have this converter:

public class InvertVisibilityConverter : IValueConverter {

    public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture) {
        if (targetType == typeof(Visibility)) {
            Visibility vis = (Visibility)value;
            return vis == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;
        }
        throw new InvalidOperationException("Converter can only convert to value of type Visibility.");
    }

    public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture) {
        throw new Exception("Invalid call - one way only");
    }
}

And this XAML:

<Button Visibility="{Binding ElementName=btn1, Path=Visibility, Converter={StaticResource InvertVisibilityConverter}}">Btn2</Button>

Which works. I'm just wondering if there's a more direct way in WPF / Silverlight to accomplish this? I don't mind having a converter, I just want to make sure there's no better way I'm not aware of.

like image 863
Adam Rackis Avatar asked Nov 04 '10 18:11

Adam Rackis


3 Answers

In this case you could do it with triggers. Example with two Buttons

<Button Name="button1">
    <Button.Style>
        <Style>
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=button2, Path=Visibility}" Value="Visible">
                    <Setter Property="Button.Visibility" Value="Hidden"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>
<Button Name="button2"/>
like image 73
Fredrik Hedblad Avatar answered Nov 19 '22 22:11

Fredrik Hedblad


Bottom line, I see no problem with what you are doing.

That said, if you have a property in the ViewModel to which Control A binds to control its visibility, I would bind Control B to the same property and invert the visibily via a separate converter. I'm not sure if I can articulate why, but that seems more natural to me (at least in lieu of any additional context around what you are doing).

like image 33
Phil Sandler Avatar answered Nov 19 '22 20:11

Phil Sandler


What you doing is fine but I tend to prefer more general converters and to keep symmetry with the built in converters.

So I would do a InverseBooleanToVisibiltyConverter that accepts booleans and returns visibility types. This matches with the built in BoolenToVisibiltyConverter

Then I would bind to the IsVisible property of the button not the Visibility property.

But that is a matter of preference really.

like image 3
Brad Cunningham Avatar answered Nov 19 '22 22:11

Brad Cunningham