2

I am trying to display items in a WinUI 3 ComboBox using SelectedValuePath and DisplayMemberPath. However, the ComboBox does not show the initial selected value.

<ComboBox
        x:Name="MyComboBox"
        ItemsSource="{x:Bind Items, Mode=OneWay}"
        SelectedValuePath="Model"
        DisplayMemberPath="Name"/>

public enum ModelEnum
{
    AAA = 0,
    BBB = 10,
    CCC = 100
}

public class AlphItem
{
    public ModelEnum Model { get; set; }
    public String Name { get; set; } = String.Empty;
}

public sealed partial class MainWindow : Window
{
    public List<AlphItem> Items { get; } =
    [
        new() { Name = "AAA", Model = ModelEnum.AAA },
        new() { Name = "BBB", Model = ModelEnum.BBB },
        new() { Name = "CCC", Model = ModelEnum.CCC }
    ];

    public MainWindow()
    {
        InitializeComponent();

        MyComboBox.SelectedValue = ModelEnum.AAA; // Initial value
    }
}

2 Answers 2

2

The issue here is you have assigned the SelectedValue, Instead try assigning the SelectedItem.
Also, while assigning the selected item assign it through the list (i.e, Itemsource).

MyComboBox.SelectedItem = Items.FirstOrDefault(i => i.Model == ModelEnum.AAA);

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

It worked! Thank you.
1

It looks like you are hitting this know issue, which doesn't let you use enum for the SelectedValue.

Unfortunately, AFAIK, there's no good workaround using the SelectedValuePath. You just need to use SelectedIndex or SelectedItem.

Also, instead of setting the initial value on the constructor, set it on the Loaded event. The value is not rendered as the initial value on my end if I set it on the constructor.

private void MyComboBox_Loaded(object sender, RoutedEventArgs e)
{
    if (sender is not ComboBox comboBox ||
        comboBox.Items.FirstOrDefault(item => (item as AlphItem)?.Model == ModelEnum.BBB) is not AlphItem initialItem)
        return;

    comboBox.SelectedItem = initialItem;
}

1 Comment

So it was a known issue, thank you. When I used the bound variable items in the constructor, it worked fine. It seems that using comboBox.Items doesn’t work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.