WPF:自定义控件上的DependencyProperty设置为value,但ViewModel上的bound属性设置为null

时间:2016-10-21 14:00:59

标签: c# wpf dependency-properties

我正在尝试创建一个可以绑定其SelectedItems属性的WPF ListView。

我从ListView继承。当引发ListView的SelectionChanged事件时,我读取了ListView的SelectedItems属性,并将DependencyProperty的值设置为它。

然后我将一个BetterListView对象添加到XAML并将其SelectedItemsBindable属性绑定到viewmodel。

虽然看起来一切正常 - 当我打破视图模型的set方法时,我看到虽然SelectedItemsBindable设置为BetterListView内的一个集合,但viewmodel将此值设为null!我做错了什么?

class BetterListView : ListView
{
    [Bindable(true)]
    [Category("Appearance")]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public IList SelectedItemsBindable
    {
        get { return GetValue(SelectedItemsBindableProperty) as IList; }
        set
        {
            SetValue(SelectedItemsBindableProperty, value);
        }
    }

    public static readonly DependencyProperty SelectedItemsBindableProperty = DependencyProperty.Register(
        "SelectedItemsBindable",
        typeof(IList), 
        typeof (BetterListView),
        new FrameworkPropertyMetadata(new List<object>(), 
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

    private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var items = SelectedItems.Cast<object>().ToList();
        SelectedItemsBindable = items;
    }

    #region constructor

    public BetterListView()
    {
        SelectionChanged += OnSelectionChanged;
    }

    #endregion
}

0 个答案:

没有答案