ここで説明したようにを使用してみてくださいICollectionView
(回答)。CollectionViewがコンボボックスを処理し、現在のアイテムを読み取って設定できます。CurrentChanged
ICollectionViewからイベントにイベントハンドラーをアタッチするだけです。
XAML:
<ComboBox
ItemsSource="{Binding Path=Items}"
DisplayMemberPath="ItemName"
IsSynchronizedWithCurrentItem="True"
Margin="8,2,8,16" />
<Label Content="{Binding Path=CurrentItem.ItemName}"/>
ViewModel:
public class ViewModel :INotifyPropertyChanged
{
private ObservableCollection<Item> _items= new ObservableCollection<Item>();
private Item _currentItem;
public ObservableCollection<Item> Items
{
get { return _items; }
set { _items= value; OnPropertyChanged("Items");}
}
public Item CurrentItem
{
get { return _currentItem; }
set { _currentItem = value; OnPropertyChanged("CurrentItem");}
}
public ICollectionView ItemsView { get; private set; }
public ViewModel()
{
Items.Add(new Item{Id = Guid.NewGuid(), Name = "Item 1"});
Items.Add(new Item{Id = Guid.NewGuid(), Name = "Item 2"});
Items.Add(new Item{Id = Guid.NewGuid(), Name = "Item 3"});
ItemsView = CollectionViewSource.GetDefaultView(Items);
ItemsView .CurrentChanged += OnItemsChanged;
ItemsView .MoveCurrentToFirst();
}
private void OnItemsChanged(object sender, EventArgs e)
{
var selectedItem = ItemsView .CurrentItem as Item;
if (selectedItem == null) return;
CurrentItem= selectedItem ;
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public class Item
{
public Guid Id { get; set; }
public string Name { get; set; }
}