Reputation: 163
I have a problem with binding to SelectedItem property of ComboBox.
There is an ObservableCollection, which is binded to ItemsSource property and another object field, which I want to bind to SelectedItem property, in the app.
But the application doesn't even start, because of Target Invocation Exception.
I don't know, if is it important to bind SelectedItem with one of the property of one instance of ItemsSource or I can use declare another property in viewmodel for it. I tried both variants. Didn't help. I've read some threads about such problem, but those solutions doesn't solve this.
<ComboBox x:Name="CategoryComboBox"
ItemsSource="{Binding CategoryList}"
DisplayMemberPath="Name"
SelectedItem="{Binding SelectedCategory, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
SelectionChanged="CategoryComboBox_SelectionChanged"
/>
public ObservableCollection<IItem> CategoryList { get; set; }
public IItem SelectedCategory
{
get
{
return _selectedCategory;
}
set
{
_selectedCategory = value;
RaisePropertyChangedEvent(nameof(SelectedCategory));
}
}
public interface IItem
{
int Id { get; set; }
string Name { get; set; }
}
private void CategoryComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var catName = (e.AddedItems[0] as IItem).Name;
vm.SelectedCategory = vm.CategoryList.Where(w => w.Name == catName).Select(s => s.Id).FirstOrDefault();
}
public void LoadLanguageList()
{
LanguageList = Repository.Current.GetLanguageList();
_selectedLanguage = LanguageList.FirstOrDefault(i => i.Id == 1);
RaisePropertyChangedEvent(nameof(SelectedLanguage));
}
In the code upper you can see the way, how I try to bind, then the collection property, selected item property and the type of items as interface.
I know, that it's impossible to create an instance of interface, but I don't know if binding object of such type is incorrect. But I tried to bind to another object type of class, which implements this interface, and the result was the same.
Upvotes: 1
Views: 167
Reputation: 937
SelectedCategory= CategoryList [0];
vm.SelectedCategory = vm.CategoryList.Where(w => w.Name == catName).FirstOrDefault();
these 2 need to be changed
Note: you don't have to create an event for SelectionChanged
. if the item is changed in ui it will automatically assign to SelectedCategory
im assuming ur using MVVM so u set data context
Upvotes: 3