【问题标题】:How do I bind the SelectedValue of a ComboBox to a Property?如何将 ComboBox 的 SelectedValue 绑定到属性?
【发布时间】:2011-04-17 16:05:27
【问题描述】:

我有一个带有 ItemsSource 的 ComboBox,我已将它绑定到 List(Of String)。

我想做的是让 XAML 在 ComboBox 的 SelectedValue 更改时更新 String 属性。我已经看到一大堆使用文本框的示例

Text="{Binding Path=MyString}"

类似的东西,但如果将来我需要将 ItemsSource 更改为 List(Of ObscureObject)...

【问题讨论】:

    标签: wpf vb.net data-binding combobox


    【解决方案1】:

    绑定到组合框的选定属性相当简单。

    XAML:

    <ComboBox ItemsSource={Binding Path=MyCollection} SelectedItem={Binding Path=MyItem}/>
    

    代码隐藏:

    public List<string> MyCollection {get; set;}
    public string MyItem {get; set;}
    

    如果要在所选项目中插入文本,则需要使用INotifyPropertyChanged

    至于您的可伸缩性问题,更新属性类型以反映集合是一个相当小的更改。否则,您可以尝试绑定到 Object,尽管这意味着您必须不断地将对象重铸回您想要的状态。

    【讨论】:

      【解决方案2】:

      您可以使用 ComboBox 的 SelectedItem 属性来实现这一点。

          <ComboBox ItemsSource="{Binding Path=YouList}" 
      SelectedItem="{Binding Path=MyString}" />
      

      当您将来更改列表时,您必须将 SelectedItem 与您的对象类型的属性绑定。

      查看这篇文章了解更多详情 -

      http://japikse.blogspot.com/2008/10/wpf-combobox-selecteditem-selectedvalue.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-25
        • 2010-09-30
        • 2015-03-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多