I want to bind the visibility property of a control in WPF to a boolean value.
I wrote a Converter based on IValueConverter
:
namespace MyApp.Converter
{
using System;
using System.Windows.Data;
public class BoolToVisibilityConverter : IValueConverter
{
public Object Convert(Object value, Type targetType, Object parameter, System.Globalization.CultureInfo culture)
{
if ((Boolean)(value)==true)
{
return "Visible";
}
return "Collapsed";
}
public Object ConvertBack(Object value, Type targetType, Object parameter, System.Globalization.CultureInfo culture)
{
...
}
}
}
And tried both: to define the converter in App.xaml and in the Window.Resources of the Window itself:
xmlns:Converters="clr-namespace:MyApp.Converter"
...
<Window.Resources>
<Converters:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter" />
</Window.Resources>
alternative in App.xaml:
xmlns:Converters="clr-namespace:MyApp.Converter"
...
<Application.Resources>
<Converters:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter" />
</Application.Resources>
Using the Converter for the visibility property compiles - but the converter is never called and thus the visibility never changes:
<Label Visibility="{Binding ShowCirle, Converter={StaticResource BoolToVisibilityConverter}}"/>
The binding itself seems ok - since the output of ShowCircle in a label updates correctly:
<Label Content="{Binding ShowCircle}"></Label>
So, what am I missing? The build compiles without errors, starts, but the binding only updates the string (for debug purposes) but not the visibility - and a breakpoint in the converter itself is never hit.
Your converter should not return a string
it should be Visiblity.Visible
or Visibility.Collapsed
.
To check if your Bindings are correct take a look at the Output-Window when debugging. If you see a Binding-Error (20,40 not sure which one) with your Property-Name then something is wrong with your binding. Maybe just a missspelling of the property.