将文本绑定到组合框中的选定项目

A T*_*res 2 c# data-binding wpf xaml combobox

我在数据库上有一个文本字段,但现在我不希望它是一个免费的开放字段,我想限制它:让我们说A,B和C.

为此,我想使用Combobox.

问题:如果在XAML中定义组合框的项目,如何将所选项目绑定到字符串属性?

XAML:

 <ComboBox SelectedValue="{Binding Path=MyProperty}"> <!-- Not working-->
   <ComboBoxItem>A</ComboBoxItem>
   <ComboBoxItem>B</ComboBoxItem>
   <ComboBoxItem>C</ComboBoxItem>
 </ComboBox>
Run Code Online (Sandbox Code Playgroud)

类:

public Class MyClass:INotifyPropertyChanged
{
private string myProperty;
public string MyProperty
{
 get{return myProperty;}
 set{
      myProperty=value;
      OnPropertyChanged("MyProperty");
    }
 }
}
Run Code Online (Sandbox Code Playgroud)

因此,用户将更改所选项,并且将在数据绑定对象上更新新值.

编辑:由于评论和答案我部分解决了问题,唯一的问题是程序启动时组合框选择是空的.我这样解决了:

<ComboBox SelectedValuePath="Content">
 <ComboBoxItem>A</ComboBoxItem>
 <ComboBoxItem>B</ComboBoxItem>
 <ComboBoxItem>C</ComboBoxItem>
  <ComboBox.SelectedValue>
   <Binding Path="MyProperty" Mode="TwoWay"/>
  </ComboBox.SelectedValue>
 </ComboBox>
Run Code Online (Sandbox Code Playgroud)

我将选定的值部分移出了Combobox的属性,并使用了属性元素sintax,这确保了在使用之前定义了集合.

m-y*_*m-y 7

Wpf ComboBox有三个选择属性和一个显示属性:

  • SelectedItem
  • SelectedValue
  • SelectedValuePath
  • DisplayMemberPath

使用时SelectedValue你也应该设置SelectedValuePath(几乎总是).了解Items在您的情况下包含一个对象的序列(ItemCollection),ComboBoxItem就像任何其他对象一样,您必须指定SelectedValuePath要绑定的(读取属性); 在这种情况下,您要访问该ComboBoxItem.Content属性(http://msdn.microsoft.com/en-us/library/system.windows.controls.contentcontrol.content(v=vs.110).aspx).

<ComboBox SelectedValue="{Binding Path=MyProperty}" SelectedValuePath="Content">
  <ComboBoxItem>A</ComboBoxItem>
  <ComboBoxItem>B</ComboBoxItem>
  <ComboBoxItem>C</ComboBoxItem>
</ComboBox>
Run Code Online (Sandbox Code Playgroud)

现在,您使用所选项目的属性绑定SelctedValue到属性,该属性恰好是您要查找的字符串.MyPropertyContent