数据绑定WPF ComboBox与XAML中定义的选择? [英] Data bound WPF ComboBox with choices defined in XAML?

查看:1521
本文介绍了数据绑定WPF ComboBox与XAML中定义的选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的viewmodel,我有一个 int 属性,我想暴露它编辑与ComboBox,有限的选择,如16,8 ,4和2.有没有一种方法来指定XAML中的选择,同时仍然将值绑定回viewmodel?我想要这样做:

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>

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

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.

推荐答案

您可以完全按照您的示例指定选择。看起来你的缺失,使它工作,是SelectedValuePath属性。没有它,SelectedValue将与SelectedItem相同。通过在ComboBox中设置SelectedValuePath =Content,您可以指定您的SelectedValue绑定而不是绑定到SelectedItem的一部分,在这种情况下,您指定为每个ComboBoxItem中的内容的Int内容。

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.

这是一个小演示,并且绑定值到一个TextBox,你可以设置项目,并通过SelectedValue绑定看到它反映在ComboBox中(反之亦然)。

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>

这篇关于数据绑定WPF ComboBox与XAML中定义的选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆