绑定到自定义依赖项属性失败

时间:2013-06-24 12:24:32

标签: c# wpf binding dependency-properties

由于ListBox控件的SelectedItems property是普通属性而不是要绑定的依赖项属性,因此我派生了ListBox并创建了一个新的依赖项属性{{1} }。

但我的XAML编译器一直给我错误

  

无法在'SelectedItemsEx'属性上设置'绑定'   输入'MyListBox'。 '绑定'只能在DependencyProperty上设置   DependencyObject。

为什么我的财产不被识别为依赖财产?感谢任何帮助,谢谢!

XAML:

SelectedItemsEx

ListBox'实施:

  <MyListBox ItemsSource="{Binding MyData}" SelectedItemsEx="{Binding SelectedEx}" 
                                            SelectionMode="Extended"> ... </MyListBox>

1 个答案:

答案 0 :(得分:3)

DependencyProperty字段必须是静态的:

public static readonly DependencyProperty SelectedItemsExProperty = ...

另请注意,为了使派生的ListBox更具可重用性,您不应该限制SelectedItemsEx属性的类型。请改用IEnumerable(或IList,如SelectedItems)。此外,无需按属性元数据指定默认值,因为它已nulldefault(<any reference type>)也是null

但是,只要SelectedItemsEx属性发生变化,您就会收到通知。因此,您必须通过属性元数据注册更改回调:

public static readonly DependencyProperty SelectedItemsExProperty =
    DependencyProperty.Register(
        "SelectedItemsEx", typeof(IEnumerable), typeof(MyListBox),
        new PropertyMetadata(SelectedItemsExPropertyChanged));

public IEnumerable SelectedItemsEx
{
    get { return (IEnumerable)GetValue(SelectedItemsExProperty); }
    set { SetValue(SelectedItemsExProperty, value); }
}

private static void SelectedItemsExPropertyChanged(
    DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
    var listBox = (MyListBox)obj;
    var oldColl = e.OldValue as INotifyCollectionChanged;
    var newColl = e.NewValue as INotifyCollectionChanged;

    if (oldColl != null)
    {
        oldColl.CollectionChanged -= listBox.SelectedItemsExCollectionChanged;
    }

    if (newColl != null)
    {
        newColl.CollectionChanged += listBox.SelectedItemsExCollectionChanged;
    }
}

private void SelectedItemsExCollectionChanged(
    object sender, NotifyCollectionChangedEventArgs e)
{
    switch (e.Action)
    {
        ...
    }
}