这是我第一次尝试绑定组合框。我在试着从我的数据库中得到值。但是,通过下面的代码,我得到了这样的结果(结果的数量与表中的行数相同):
GUITest.DB.Structure
在我的项目的GUITest ->命名空间中,structure.cs所在的DB ->文件夹。
private ObservableCollection<Structure> _lists;
public ObservableCollection<Structure> Lists
{
get { return _lists; }
set
{
_lists = value;
NotifyOfPropertyChange("Lists");
}
}
public ObservableCollection<Structure> GetStructures()
{
ObservableCollection<Structure> products = new ObservableCollection<Structure>();
using (SqlConnection conn =
new SqlConnection(ConfigurationManager.ConnectionStrings["StringConnexion"].ConnectionString))
{
conn.Open();
SqlCommand cmdNotes =
new SqlCommand("SELECT * FROM Structure", conn);
using (SqlDataReader reader = cmdNotes.ExecuteReader())
{
var ordinals = new
{
CodeStr = reader.GetOrdinal("CODE_STR"),
NomStr = reader.GetOrdinal("NOM_STR"),
};
while (reader.Read())
{
var temp = new TableStructure();
temp.CodeStr = reader.GetString(ordinals.CodeStr);
temp.NomStr = reader.GetString(ordinals.NomStr);
products.Add(temp.SqlProduct2Product());
}
}
}
return products;
}
public CreateAccountViewModel()
{
_lists = new ObservableCollection<Structure>();
Lists = GetStructures();
}XAML:
<ComboBox SelectedItem="{Binding Path=NomStr}" ItemsSource="{Binding Lists}"></ComboBox>发布于 2018-07-27 18:09:41
正如注释中所指出的,您希望DisplayMemberPath而不是SelectedItem
DisplayMemberPath说“将此属性(作为路径)显示为ItemTemplate”,对于X的路径,它在功能上等效(尽管不是代码等效):
<ComboBox>
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=X}"/>
</DataTemplate>
</ComboBox.ItemTemplate
</ComboBox>这就是为什么没有Binding扩展的原因,框架为您提供了它。
SelectedItem只是指,当前选择的组合框。它不会以任何方式影响显示器。
https://stackoverflow.com/questions/51543820
复制相似问题