У меня есть ObservableCollection
строк, которые заполняют ItemsSource
из ComboBox
. Каждый раз, когда пользователь выбирает элемент, этот элемент удаляется из ItemsSource
. Вот общий код:
ViewModel.cs
public ObservableCollection<NotifyingProperty<string>> CurrentItems { get; }
public ObservableCollection<string> SelectableItems { get; set;}
private void Initialize() {
foreach (var item in CurrentItems) item.PropertyChanged += CurrentItems_PropertyChanged;
}
private void CurrentItems_PropertyChanged(object sender, PropertyChangedEventArgs e) {
SelectableItems = new ObservableCollection<string>(...); // Remove items that are selected
OnPropertyChanged("SelectableItems");
View.xaml
<ItemsControl ... ItemsSource="{Binding CurrentItems}" VirtualizingPanel.IsVirtualizing="False">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<ComboBox e:ComboBoxItemsSourceDecorator.ItemsSource="{Binding RelativeSource={Relative Source FindAncestor, AncestorType={x:Type ItemsControl}}, Path=DataContext.SelectableItems, UpdateSourceTrigger=PropertyChanged, Converter={StaticResouurce ItemToDisplayConverter}, Mode=TwoWay}"
SelectedValue={Binding Value, Converter={StaticResource ItemToDisplayConverter}, UpdateSourceTrigger=PropertyChanged}"
SelectedValuePath=""/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
ItemToDisplayConverter.cs
public class ItemToDisplayConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
ObservableCollection<string> valArray = value as ObservableCollection<string>;
if (valArray != null) { ... } // Add spaces in camel case within the array of strings into newArray
return newArray;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
string val = value as string;
return val.Replace(" ", "");
}
ComboBoxItemsSourceDecorator
был найден в ответе здесь .
Я читал различные посты [ здесь и здесь ] на SO, описывающие, как обновитьItemsSource
в ComboBox
обнуляет все значения SelectedItem
(и предположительно SelectedValue
).
Большая часть кода работает. Когда пользователь выбирает элемент, он успешно удаляется из ItemsSource
, и декоратор пытается очистить и сбросить привязки. Тем не менее, текст в ComboBox
всегда пуст.
Отладка кода дала такой интересный результат:
var target = element as Selector
target.SelectedValue
is "ItemName "
target.InternalSelectedValue
is DependencyProperty.UnsetValue
Есть ли причина этого несоответствия? Кроме того, есть ли способ динамически изменить ComboBox
ItemsSource
, когда он обернут в ItemsControl
?