[英]Bind text to selected item in combobox
我在數據庫上有一個文本字段,但現在我不希望它是一個免費的開放字段,我想將其限制為:假設 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>
我將選定的值部分移出了 Combobox 的屬性,並使用了屬性元素 sintax,這確保了在使用之前定義了集合。
Wpf ComboBox
具有三個選擇屬性和一個顯示屬性:
SelectedItem
SelectedValue
SelectedValuePath
DisplayMemberPath
使用SelectedValue
您還應該設置SelectedValuePath
(幾乎總是)。 了解您案例中的Items
包含ComboBoxItem
對象的序列( ItemCollection
),並且就像任何其他對象一樣,您必須指定要綁定到的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>
現在,您正在使用所選項目的Content
屬性將SelctedValue
綁定到MyProperty
屬性,這恰好是您要查找的字符串。
我不喜歡硬編碼組合框項目。 在這種情況下如此簡單,我將在組合框的 itemsource 中列出該類型的列表。 如果它比字符串列表更復雜,我會在您的數據庫中創建一個查找表並使用它。 對於字符串列表路由,它將類似於:
public List<String> LetterTypes { get; set; }
public String SelectedLetterType { get; set; }
國際貿易商:
LetterTypes = new List<String> { A, B, C }
然后在您的視圖中:
<ComboBox ItemsSource="{Binding LetterTypes}" SelectedItem="{Binding SelectedLetterType}" />
我看到您已經找到了解決問題的方法,但也許為了將來參考,這可能是填充組合框的另一種方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.