自定义控件不保存对属性的更改

时间:2018-01-30 15:03:35

标签: wpf custom-controls dependency-properties

我使用此DependencyProperty来存储字符串集合:

public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register( nameof( ItemsSource ) , typeof( IEnumerable<string> ) , typeof( MyClass) , new FrameworkPropertyMetadata( new List<string>() , FrameworkPropertyMetadataOptions.BindsTwoWayByDefault ) );

在ItemsSource的属性中,我试图过滤掉已经选择的字符串。喜欢这个

SetValue( ItemsSourceProperty , source.Except( target ).ToList() );
return (IEnumerable<string>) GetValue( ItemsSourceProperty );

source包含所有可能的值,以所选值为目标。 source.Except(target).ToList()工作正常,但结果永远不会存储在DependencyProperty中。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

是的,我正在使用Binding。这是自定义控件的属性:

public IEnumerable<string> ItemsSource
{
    get
    {
        var source = (IEnumerable<string>) GetValue( ListBoxSourceProperty);
        var target = (IEnumerable<string>) GetValue( SelectedItemsProperty);


        if ( source == null )
        {
            source = (IEnumerable<string>) GetValue( ItemsSourceProperty );
            ListBoxSource = source;
        }


        if ( source.ToList().Count == 0 )
        {
            source = (IEnumerable<string>) GetValue( ItemsSourceProperty );
            ListBoxSource = source;
        }

        var tmp = source.Except( target ).ToList(); // tmp.Count() = 5

        SetValue( ItemsSourceProperty , tmp ); // nothing is written here

        var tmp2 =(IEnumerable<string>) GetValue( ItemsSourceProperty );  // tmp2.Count() = 6 !!!


        OnPropertyChanged( "ItemsSource" );
        return tmp;  // the control displays 6 elements every time
    }

    set
    {
        SetValue( ItemsSourceProperty , value );
    }
}

这是DataContext中的属性

public ObservableCollection<string> ItemSource
{
    get
    {
        if ( _itemsSource == null )
        {
            _itemsSource = new ObservableCollection<string>( _catalog );
        }

        return _itemsSource;
    }
    set { /*_itemsSource = value;*/ }
}

_catalog和_itemSource的类型为List

最后是xaml文件中的绑定表达式:

<local:MyControl ItemsSource="{Binding ItemSource}" />