尝试将 aICollectionView
与 结合使用IsSynchronizedWithCurrentItem
。ICollectionView 负责所有与组合框相关的操作。您还可以设置当前选定的项目。
xml:
<ComboBox ItemsSource="{Binding AllValues}"
IsSynchronizedWithCurrentItem="True"
Width="150"
Margin="5,0,0,0"/>
视图模型
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Data;
namespace ComboBoxBinding
{
public class ViewModelSpike : INotifyPropertyChanged
{
private ObservableCollection<Model> _allValues = new ObservableCollection<Model>();
private Model _selectedValue;
public ObservableCollection<Model> AllValues
{
get { return _allValues; }
set { _allValues = value; OnPropertyChanged("AllValues");}
}
public Model SelectedValue
{
get { return _selectedValue; }
set { _selectedValue = value; OnPropertyChanged("SelectedValue");}
}
public ICollectionView ModelsView { get; private set; }
public ViewModelSpike()
{
//First init / load AllValues here...
ModelsView = CollectionViewSource.GetDefaultView(AllValues);
ModelsView.CurrentChanged += OnCurrentModelChanged;
//You can also set the current selected item / initial selected item
//ModelsView.MoveCurrentTo(DesiredModel from AllValues)
}
private void OnCurrentModelChanged(object sender, EventArgs e)
{
if (ModelsView.CurrentItem == null) return;
var selectedValue = ModelsView.CurrentItem as Model;
if (selectedValue == null) return;
SelectedValue = selectedValue;
if (CVSCollection.View != null) CVSCollection.View.Refresh();
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}