1

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.

4
  • You should bind to SelectedValue instead since "1" != ComboBoxItem Commented Sep 4, 2023 at 13:54
  • Nope. Has no effect. If I bind it via SelectedValue, each change of MyProp clears the ComboBox but does not set the correct value. Commented Sep 4, 2023 at 14:19
  • Yes, you are right That will break in the reverse this time ComboBoxItem != "1". It seems there is no easy way to accomplish this. Either you should use the items source or create a weird value converter that converts between ComboBoxItem string and vice versa. Commented Sep 4, 2023 at 14:26
  • If you bind to Text and set IsEditable to true, it will work. Commented Sep 4, 2023 at 14:42

1 Answer 1

4

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>
Sign up to request clarification or add additional context in comments.

Comments

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.