Problem with ComboBox Binding to IEnumerable<T> - discards SelectedItem
Describe the bug
Simple use case is: Binding a collection of items to a ComboBox and set an initial selected item. This seems easy - but has drive me crazy!
It seems the problem is related to Linq Select with initializing new items returning an IEnumerable
In my example for reproducing there is Select(a => new Test(a.Name, a.Value)) which does logical nothing but initializes new objects and returns IEnumerable
NOTE: I've tested the exactly same code on WPF and .NET 6 working as expected without problems!
Steps to reproduce the bug
The following example uses normal View - ViewModel concept based on CommunityToolkit.Mvvm 7.1.2. I've also tested with manually INotifyPropertyChanged implementation - it's the same.
Create a ComboBox, a list with items, a selected item property. Then load in constructor the list and set the selected item.
View.xaml (Note: DataContext is set to ViewModel)
<ComboBox DisplayMemberPath="Name" ItemsSource="{Binding Items}" SelectedItem="{Binding Selected, Mode=TwoWay}"
ViewModel.cs
// simple class holding multiple properties - also tested normal class with getter and setter - it's the same
public record Test(string Name, string Value);
// collection holding items
[ObservableProperty]
private IEnumerable<Test> _items;
// selected item
[ObservableProperty]
private Test _selected;
// load items in constructor of VM and set selected item
public ViewModel(){
Items = new List<Test>{ new Test(Name: "A" , Value: "A"), new Test(Name: "B", Value:"B")}
// WARNING: following line triggers the problem! Remove it and anything is working again!
.Select(a => new Test(a.Name, a.Value));
Selected = Items.First(c => c.Name == "B");
}
Expected behavior
ComboBox filled with values and one value (B) is selected after load.
Screenshots
No response
NuGet package version
None
Windows version
Windows 11 (22H2): Build 22621
Additional context
Visual Studio 2022 (all Updates), .NET 7, win-x64, WinUI 3 (Microsoft.WindowsAppSDK in Version 1.2.230118.102)
I also encountered this problem. The current solution is to update 'Selected' after the View is loaded.
Any updates on this issue?
Any Update?