ICollectionView
と組み合わせて使用してみてくださいIsSynchronizedWithCurrentItem
。ICollectionView は、コンボボックスに関連するすべてのアクションを処理します。現在選択されているアイテムを設定することもできます。
Xaml:
<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));
}
}
}