Проблема двустороннего связывания неизвестного объекта в свойстве зависимостей пользовательского элемента управления WPF
У меня есть пользовательский элемент управления - реализовано для автозаполнения TextBox. Я получил все идеи из следующего вопросаСоздайте пользовательский элемент управления с комбинацией нескольких элементов управления в WPF C #, В этом пользовательском элементе управления предлагается следующий код для добавления элемента:его отлично работает и двусторонняя привязка тоже.
(this.ItemsSource as IList<string>).Add(this._textBox.Text);
Но я изменил следующий код на неизвестный объект, поэтому я изменилIList<string>
вIList<object>
(this.ItemsSource as IList<object>).Add(item);
XAML:
<local:BTextBox
ItemsSource="{Binding Collection}"
ProviderCommand="{Binding AutoBTextCommand}"
AutoItemsSource="{Binding SuggCollection}" />
Но это не обновляет свойство ViewModelCollection
, Я тоже попробовал следующие изменения в xaml
ItemsSource="{Binding Collection, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
Я не знаю, где я сделал ошибку.
функциональность:TextBox
внутриCustomControl
принимает входные данные от пользователя и запускаетProviderCommand
эта команда фильтрует удаленные данные на основе пользовательского ввода и отправляет отфильтрованную коллекцию черезAutoItemsSource
, это свойство связано какItemsSource
изListBox
внутри этогоCustomControl
выбрать пункт. Мы можем выбрать пункт изListBox
Элемент, нажав на элемент, он запускает командуAddCommand
который находится вCustomControl
Класс, это добавить выбранный элемент вItemSource
СобственностьCustomControl
, У меня естьПроблема двустороннего связывания в этой собственностиItemsSource
, Только из этого свойства мы можем получить выбранный элемент как коллекцию.
Вотмой полный исходный код
Код C # пользовательского элемента управления:
public class BTextBox : ItemsControl
{
static BTextBox()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(BTextBox), new FrameworkPropertyMetadata(typeof(BTextBox)));
}
#region Private Members
private TextBox _textBox;
private ItemsControl _itemsView;
#endregion
#region Dependency Property Private Members
public static readonly DependencyProperty ProviderCommandProperty = DependencyProperty.Register("ProviderCommand", typeof(ICommand), typeof(BTextBox), new PropertyMetadata(null));
public static readonly DependencyProperty AutoItemsSourceProperty = DependencyProperty.Register("AutoItemsSource", typeof(IEnumerable<dynamic>), typeof(BTextBox), new PropertyMetadata(null, OnItemsSourceChanged));
#endregion
#region Dependency Property Public members
public IEnumerable<dynamic> AutoItemsSource
{
get { return (IEnumerable<dynamic>)GetValue(AutoItemsSourceProperty); }
set { SetValue(AutoItemsSourceProperty, value); }
}
#endregion
#region Listener Methods
private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var tb = d as BTextBox;
if ((e.NewValue != null) && ((tb.ItemsSource as IList<object>) != null))
{
(tb.AutoItemsSource as IList<object>).Add(e.NewValue);
}
}
#endregion
#region Override Methods
public override void OnApplyTemplate()
{
this._textBox = this.GetTemplateChild("PART_TextBox") as TextBox;
this._itemsView = this.GetTemplateChild("PART_ListBox") as ItemsControl;
this._textBox.TextChanged += (sender, args) =>
{
if (this.ProviderCommand != null)
{
this.ProviderCommand.Execute(this._textBox.Text);
}
};
base.OnApplyTemplate();
}
#endregion
#region Command
public ICommand ProviderCommand
{
get { return (ICommand)GetValue(ProviderCommandProperty); }
set { SetValue(ProviderCommandProperty, value); }
}
public ICommand AddCommand
{
get
{
return new DelegatingCommand((obj) =>
{
(this.ItemsSource as IList<object>).Add(obj);
});
}
}
#endregion
}
Generic.xaml Код
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SampleControl">
<Style TargetType="{x:Type local:BTextBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:BTextBox}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="40"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBox x:Name="PART_TextBox" Grid.Row="0" Width="*" VerticalAlignment="Center" />
<ListBox ItemsSource="{TemplateBinding AutoItemsSource}" Grid.Row="1" x:Name="PART_ListBox_Sugg" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Value.IsChecked}" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:BTextBox}}, Path=AddCommand}" CommandParameter="{Binding }" Foreground="#404040">
<CheckBox.Content>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding }" Visibility="Visible" TextWrapping="Wrap" MaxWidth="270"/>
</StackPanel>
</CheckBox.Content>
</CheckBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
MainWindow.xaml Код
<Window x:Class="SampleControl.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SampleControl"
Title="MainWindow" Height="400" Width="525">
<Grid>
<local:BTextBox
ItemsSource="{Binding Collection}"
ProviderCommand="{Binding AutoBTextCommand}"
AutoItemsSource="{Binding SuggCollection}" />
</Grid>
</Window>
MainWindow.xaml'sКод позади кода C #
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new StringModel();
}
}
У меня есть две ViewModels
ViewModel # 1StringModel
class StringModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private ObservableCollection<string> _collection = new ObservableCollection<string>();
private ObservableCollection<string> _suggCollection = new ObservableCollection<string>();
private ObservableCollection<string> _primaryCollection = new ObservableCollection<string>();
public ObservableCollection<string> Collection
{
get { return _collection; }
set
{
_collection = value;
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Collection"));
}
}
public ObservableCollection<string> SuggCollection
{
get { return _suggCollection; }
set
{
_suggCollection = value;
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("SuggCollection"));
}
}
public StringModel()
{
_primaryCollection = new ObservableCollection<string> {
"John", "Jack", "James", "Emma", "Peter"
};
}
public ICommand AutoBTextCommand
{
get
{
return new DelegatingCommand((obj) =>
{
Search(obj as string);
});
}
}
private void Search(string str)
{
SuggCollection = new ObservableCollection<string>(_primaryCollection.Where(m => m.ToLowerInvariant().Contains(str.ToLowerInvariant())).Select(m => m));
}
}
ViewModel # 2IntModel
class IntModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private ObservableCollection<int> _collection = new ObservableCollection<int>();
private ObservableCollection<int> _suggCollection = new ObservableCollection<int>();
private ObservableCollection<int> _primaryCollection = new ObservableCollection<int>();
public ObservableCollection<int> Collection
{
get { return _collection; }
set
{
_collection = value;
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Collection"));
}
}
public ObservableCollection<int> SuggCollection
{
get { return _suggCollection; }
set
{
_suggCollection = value;
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("SuggCollection"));
}
}
public IntModel()
{
_primaryCollection = new ObservableCollection<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 16, 17, 18, 19, 20 };
}
public ICommand AutoBTextCommand
{
get
{
return new DelegatingCommand((obj) =>
{
Search(obj as string);
});
}
}
private void Search(string str)
{
int item = 0;
int.TryParse(str, out item);
SuggCollection = new ObservableCollection<int>(_primaryCollection.Where(m => m == item).Select(m => m));
}
}