0
votes

I have problem with binding visibility in listbox-item template with property in parent object. Here is a little snippet from custom xaml style template:

<!-- DATA BINDING ITEM TEMPLATE -->
<StackPanel Orientation="Vertical">
    <TextBlock Height="19"
        ....
        Text="{Binding InfoTop}"/>
    <Rectangle Height="1"
        ....
        Visibility="{Binding _linesVisibility[0], RelativeSource={RelativeSource AncestorType=my:PatientsList}}"/>
    <TextBlock Height="19"
        ....
        Text="{Binding InfoMiddle}"
        Visibility="{Binding _linesVisibility[0], ElementName=patientsControl}"/>
    <Rectangle Height="1"
        ....
        Visibility="{Binding _linesVisibility[1]}"/>
    <TextBlock Height="19"
        ....
        Text="{Binding InfoBottom}"
        Visibility="{Binding _linesVisibility[1]}"/>
</StackPanel>

I managed to bind Text value by assigning ItemsSource in code file but i can't bind Visibility. As you can see i tried some different ideas but none of them work.

I have public variable public Visibility[] _linesVisibility = new Visibility[2]; in my custom control. This control contains listbox with custom style as above. How to bind properly my _linesVisibility to listbox-item style ?

1

1 Answers

0
votes

You can't bind directly to an array:

Visibility="{Binding _linesVisibility[1]}"

This will not work.

You need to bind to a property and your class needs to implement INotifyPropertyChanged:

private Visibility backingVariable;
public Visbilility PublicProperty
{
    get { return backingVariable; }
    set
    {
        backingVariable = value;
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs("PublicVariable"));
        }   
    }
}

It doesn't have to be a property of type Visibility. It can be any type as long as you bind through a converter that returns Visibility:

public class BoolToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        bool visibility = (bool)value;
        return visibility ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        Visibility visibility = (Visibility)value;
        return (visibility == Visibility.Visible);
    }
}

Usage:

Visibility="{Binding SomeBoolean, Converter={StaticResource boolToVisibilityConverter}}"

where the converter is declared in XAML like this:

<UserControl.Resources>
    <globalConverters:BoolToVisibilityConverter x:Key="boolToVisibilityConverter" />
</UserControl.Resources>