The other way to solve this problem is using Converter
on Binding
. when you use binding to bind SelectedItem
, WPF will check the reference of SelectedItem
against all objects inside ItemsSource
property and of course if there was no match, SelectedItem
will be empty. using Converter
you can tell WPF that how it should match SelectedItem
.
In this case you just need find SelectedItem
among ItemsSource
and return it to Binding
. so follow these steps:
1- Create a class and implement IValueConverter
. It has two methods: Convert
and ConvertBack
2- for Convert
method do something like this:
public class MySelecteItemBindingConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
var mySelectedItem = value as MySelectedItemType;
var myItemsSource = parameter as List<MySelectedItemType>;
var matchedItem = myItemsSource.FirstOrDefault(i=>i.Id == mySelectedItem.Id);
return matchedItem;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
// Do just like Convert method
}
}
3- Use this Converter
on your Binding
like this:
var myBinding = new Binding("YourBindingPath");
myBinding.Converter = new MySelectedItemBindingConverter();
myBinding.ConverterParameter = myItemsSource; //this is List<MySelectedItemType> in this example
myCombo.SetBinding(ComboBox.SelectedItemProperty, myBinding);
Note: if you want to do binding from XAML
you can not pass ConverterParameter
like this, instead you should create a static
list and use that as ItemsSource
or use MultiBinding
to pass your ConverterParameter
using a trick. here there is a good and simple explanation about it: Binding ConverterParameter