0

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

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

不能在“MyListBox”类型的“SelectedItemsEx”属性上设置“绑定”。只能在 DependencyObject 的 DependencyProperty 上设置“绑定”。

为什么我的属性不被识别为依赖属性?任何帮助表示赞赏,谢谢!

XAML:

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

列表框的实现:

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

1 回答 1

3

DependencyProperty字段必须是静态的:

public static readonly DependencyProperty SelectedItemsExProperty = ...

另请注意,为了使您的派生 ListBox 更具可重用性,您不应限制SelectedItemsEx属性的类型。改用IEnumerable(或IList喜欢SelectedItems)。此外,不需要通过属性元数据指定默认值,因为它null已经是并且default(<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)
    {
        ...
    }
}
于 2013-06-24T13:09:56.070 回答