数据绑定WPF ComboBox与XAML中定义的选项?

Ran*_*ngy 10 c# data-binding wpf combobox mvvm

在我的viewmodel上我有一个int属性,我想用ComboBox公开它进行编辑,有一组有限的选择,比如16,8,4和2.有没有办法在XAML中指定选项,还是将值绑定回viewmodel?我想做这样的事情:

<ComboBox SelectedValue="{Binding MyIntProperty}">
    <ComboBoxItem>16</ComboBoxItem>
    <ComboBoxItem>8</ComboBoxItem>
    <ComboBoxItem>4</ComboBoxItem>
    <ComboBoxItem>2</ComboBoxItem>
</ComboBox>
Run Code Online (Sandbox Code Playgroud)

我知道我可以装配一个List<int>代码并将其设置为ItemsSource,但我希望有一种方法可以做到这一点,不涉及viewmodel中的额外属性,它暴露了在代码中创建的集合.

rmo*_*ore 13

您可以在示例中完全按照您的方式指定您的选择.为了使其有效,您看起来像是SelectedValuePath属性.没有它,SelectedValue将与SelectedItem相同.通过在ComboBox中设置SelectedValuePath ="Content",您可以指定SelectedValue绑定仅绑定到SelectedItem的一部分,在这种情况下,您指定为每个ComboBoxItem中的内容的Int内容.

这是一个带有它的小演示,并且还将值绑定到TextBox,您可以在其中设置项目并通过SelectedValue绑定查看它在ComboBox中的反映(反之亦然).

<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>
Run Code Online (Sandbox Code Playgroud)