我在数据库上有一个文本字段,但是现在我不希望它成为一个自由的开放字段,我想将其限制为:假设A,B和C。
为此,我想使用一个组合框。
问题:鉴于组合框的项目是在XAML中定义的,我如何将所选项目绑定到字符串属性?
XAML:
<ComboBox SelectedValue="{Binding Path=MyProperty}"> <!-- Not working-->
<ComboBoxItem>A</ComboBoxItem>
<ComboBoxItem>B</ComboBoxItem>
<ComboBoxItem>C</ComboBoxItem>
</ComboBox>
班级:
public Class MyClass:INotifyPropertyChanged
{
private string myProperty;
public string MyProperty
{
get{return myProperty;}
set{
myProperty=value;
OnPropertyChanged("MyProperty");
}
}
}
因此,用户将更改所选项目,并且新值将在数据绑定对象上更新。
编辑:感谢注释和答案,我部分解决了问题,唯一的问题是程序启动时组合框选择为空。我这样解决了:
<ComboBox SelectedValuePath="Content">
<ComboBoxItem>A</ComboBoxItem>
<ComboBoxItem>B</ComboBoxItem>
<ComboBoxItem>C</ComboBoxItem>
<ComboBox.SelectedValue>
<Binding Path="MyProperty" Mode="TwoWay"/>
</ComboBox.SelectedValue>
</ComboBox>
我将选定的值部分移出了“组合框”的属性,并使用了属性元素sintax,这确保了在使用之前定义了集合。
WpfComboBox
具有三个选择属性和一个显示属性:
SelectedItem
SelectedValue
SelectedValuePath
DisplayMemberPath
使用时,SelectedValue
还应该设置SelectedValuePath
(几乎总是)。要了解的是Items
,您的案例中包含对象的序列(ItemCollection
),ComboBoxItem
就像其他任何对象一样,您必须指定SelectedValuePath
要绑定到的(read属性);在这种情况下,您要访问ComboBoxItem.Content
属性(http://msdn.microsoft.com/zh-cn/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>
现在,您将使用所选项目的属性SelctedValue
将MyProperty
属性绑定到该属性Content
,该属性恰好是您要查找的字符串。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句