在代码中绑定到变量和转换器

时间:2014-09-26 06:28:49

标签: c# wpf binding

我试图仅在bool ListBoxItem为真时才显示isInEditMode。这是我的变量:

private bool isInEditMode
{
    get { return Convert.ToBoolean(GetValue(IsInEditMode_Property)); }
    set { SetValue(IsInEditMode_Property, value); }
}

public static readonly DependencyProperty IsInEditMode_Property = DependencyProperty.Register("isInEditMode", typeof(bool), typeof(MainWindow), new PropertyMetadata(null));

这是我添加ListBoxItem

的地方
SurfaceListBoxItem slbi = new SurfaceListBoxItem();    

Binding visibilityBinding = new Binding("Visibility");
visibilityBinding.Source = isInEditMode;
visibilityBinding.Converter = new BoolToVisibility();
visibilityBinding.NotifyOnTargetUpdated = true;
slbi.SetBinding(SurfaceListBoxItem.VisibilityProperty, visibilityBinding);                    

myListBox.Items.Add(slbi);

然而,当更改isInEditMode时,转换器没有被触发。什么地方出了错?这是我的转换器btw,非常直接:

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    if (System.Convert.ToBoolean(value) == true)
        return System.Windows.Visibility.Visible;
    else
        return System.Windows.Visibility.Collapsed;
}

我在XAML中进行了快速测试,但这有效:

<Grid Visibility="{Binding Path=isInEditMode, ElementName=myMainWindow, Converter={StaticResource BoolToVisibility}, NotifyOnTargetUpdated=True}" />

1 个答案:

答案 0 :(得分:1)

您构建Binding是错误的。 Source是对象,即绑定操作的数据源。 Path(您通过ctor参数设置它)是数据源中数据属性的路径。

因此,Binding应如下所示:

var visibilityBinding = new Binding("isInEditMode");
visibilityBinding.Source = this;
visibilityBinding.Converter = new BoolToVisibility();
visibilityBinding.NotifyOnTargetUpdated = true;

// here you setting the target property - VisibilityProperty
slbi.SetBinding(SurfaceListBoxItem.VisibilityProperty, visibilityBinding);