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

本文关键字:属性 失败 依赖 自定义 绑定 | 更新日期: 2023-09-27 18:19:36

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

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

不能在的"SelectedItemsEx"属性上设置"Binding"键入"MyListBox"。只能在DependencyProperty上设置"Binding"DependencyObject的。

为什么我的属性不被识别为依赖属性?感谢您的帮助!

XAML:

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

ListBox的实现:

public class MyListBox : ListBox
{
    public readonly DependencyProperty SelectedItemsExProperty =
            DependencyProperty.Register("SelectedItemsEx", 
                typeof(ObservableCollection<MyItemsDataType>), 
                typeof(MyListBox), 
                new PropertyMetadata(default(ObservableCollection<MyItemsDataType>)));

    public ObservableCollection<MyItemsDataType> SelectedItemsEx
    {
        get
        {
            var v = GetValue(SelectedItemsExProperty);
            return (ObservableCollection<MyItemsDataType>)v;
        }
        set { SetValue(SelectedItemsExProperty, value); }
    }
    protected override void OnSelectionChanged(SelectionChangedEventArgs e)
    {
        base.OnSelectionChanged(e);
        if (SelectedItemsEx != null)
        {
            SelectedItemsEx.Clear();
            foreach (var item in base.SelectedItems)
            {
                SelectedItemsEx.Add((MyItemsDataType)item);
            }
        }
    }

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

DependencyProperty字段必须是静态的:

public static readonly DependencyProperty SelectedItemsExProperty = ...

还要注意,为了使派生的ListBox更加可重用,您不应该约束SelectedItemsEx属性的类型。请改用IEnumerable(或类似于SelectedItemsIList)。此外,不需要通过属性元数据指定默认值,因为它已经是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)
    {
        ...
    }
}
相关文章: