Silverlight绑定对父类属性的可见性

时间:2012-06-08 08:11:43

标签: silverlight binding parent visibility

我在listbox-item模板中绑定可见性与父对象中的属性有问题。这是一个来自自定义xaml样式模板的小片段:

<!-- 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>

我设法通过在代码文件中分配ItemsSource来绑定Text值,但我无法绑定Visibility。正如你所看到的,我尝试了一些不同的想法,但没有一个能够发挥作用。

我的自定义控件中有公共变量public Visibility[] _linesVisibility = new Visibility[2];。此控件包含具有上述自定义样式的列表框。如何正确绑定_linesVisibility到listbox-item样式?

1 个答案:

答案 0 :(得分:0)

您不能直接绑定到数组:

Visibility="{Binding _linesVisibility[1]}"

这不起作用。

您需要绑定到一个属性,您的类需要实现INotifyPropertyChanged

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

它不必是Visibility类型的属性。只要您通过返回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);
    }
}

用法:

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

转换器在XAML中声明如下:

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