Search code examples
c#xamlcomboboxwinui-3winui

Binding selected item in ComboBox in WinUI3


I've a ComboBox in WinUI3 with two items manual added:

<ComboBox Width="200" SelectedItem="{Binding MyProp, Mode=TwoWay}">
   <ComboBoxItem Content="1"/>
   <ComboBoxItem Content="2"/>
</ComboBox>

Even if MyProp is set to "1" or "2" initially, the Combobox's text is empty. No item is selected. And if I select one of these items during runtime as user, the value is not written back into MyProp.

But the binding and ViewModel works fine, since a TextBox with the same TwoWay-Binding is working fine in both directions:

<TextBox Text="{Binding MyProp, Mode=TwoWay}"></TextBox>

Do I've to bind the items itself too via a list in the view model? Hoped, to define two ComboboxItem in the XAML is enough.


Solution

  • Since you have ComboBoxItem as items, you need to target the Content property. This should work:

    <ComboBox
        SelectedValue="{Binding MyProp, Mode=TwoWay}"
        SelectedValuePath="Content">
        <ComboBoxItem Content="1" />
        <ComboBoxItem Content="2" />
    </ComboBox>
    

    But you can avoid using ComboBoxItem explicitly and make it simple:

    <ComboBox
        SelectedValue="{Binding MyProp, Mode=TwoWay}">
        <x:String>1</x:String>
        <x:String>2</x:String>
    </ComboBox>