On my viewmodel I've got an int
property and I want to expose it for editing with a ComboBox, with a limited set of choices, such as 16, 8, 4 and 2. Is there a way to specify the choices in the XAML, while still binding the value back to the viewmodel? I'd want to do something like this:
<ComboBox SelectedValue="{Binding MyIntProperty}">
<ComboBoxItem>16</ComboBoxItem>
<ComboBoxItem>8</ComboBoxItem>
<ComboBoxItem>4</ComboBoxItem>
<ComboBoxItem>2</ComboBoxItem>
</ComboBox>
I know I could rig up a List<int>
in code and set that as the ItemsSource, but I'm hoping there's a way to do this that doesn't involve an extra property in the viewmodel that exposes a collection created in code.
You can specify your choices exactly as you are in your example. What it looks like your missing, to make it work, is the SelectedValuePath property. Without it, the SelectedValue would be the same as the SelectedItem. By setting SelectedValuePath="Content" in the ComboBox you can specify that your SelectedValue binding is instead binding to just a portion of the SelectedItem, in this case the Int content you specified as the content in each ComboBoxItem.
Here's a small demo with it, and also binding the value to a TextBox, where you can set the item and see it reflected in the ComboBox through the SelectedValue binding (or vice versa).
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Set Value:" />
<TextBox Text="{Binding MyIntProperty, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Select Value:" />
<ComboBox SelectedValue="{Binding MyIntProperty}" SelectedValuePath="Content">
<ComboBoxItem>2</ComboBoxItem>
<ComboBoxItem>4</ComboBoxItem>
<ComboBoxItem>6</ComboBoxItem>
<ComboBoxItem>8</ComboBoxItem>
<ComboBoxItem>16</ComboBoxItem>
</ComboBox>
</StackPanel>
</StackPanel>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With