0

我在列表框项模板中与父对象中的属性绑定可见性有问题。这是自定义 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 来绑定文本值,但我无法绑定可见性。如您所见,我尝试了一些不同的想法,但都没有奏效。

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

4

1 回答 1

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"));
        }   
    }
}

它不必是 type 的属性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>
于 2012-06-08T08:20:46.973 回答