Пользовательский элемент управления не сохраняет изменения в свойстве
Я использую этот 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.Except( target).ToList() работает нормально, но результат никогда не сохраняется в DependencyProperty.
Что я делаю неправильно?
1 ответ
Да, я использую 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}" />