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.
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"/>
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With