microsoft-ui-xaml icon indicating copy to clipboard operation
microsoft-ui-xaml copied to clipboard

Problem with ComboBox Binding to IEnumerable<T> - discards SelectedItem

Open th0masj0 opened this issue 3 years ago • 3 comments

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. After setting Items collection the SelectedItem is set (like normal) via binding. BUT: Nothing is selected after load. Catching laoded event of ComboBox tells me that SelecteItem is null! The SelectedItem is discarded.

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. Remove this line and everything is working fine! Please tell me why this is happing?

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)

th0masj0 avatar Mar 31 '23 08:03 th0masj0

I also encountered this problem. The current solution is to update 'Selected' after the View is loaded.

BeardedBoy avatar Apr 24 '23 10:04 BeardedBoy

Any updates on this issue?

greatoceansoftware avatar Jan 11 '24 05:01 greatoceansoftware

Any Update?

acepasag100 avatar Apr 11 '24 17:04 acepasag100