开发者

Data bound WPF ComboBox with choices defined in XAML?

开发者 https://www.devze.com 2022-12-14 01:15 出处:网络
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,

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 开发者_StackOverflowproperty 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>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号