Wpf 如何将ComboBox或ComboboxEdit绑定到数据表
有人能帮我设置数据表中的combobox或combobox编辑值吗? 在WinForms中是这样的:Wpf 如何将ComboBox或ComboboxEdit绑定到数据表,wpf,winforms,combobox,datatable,Wpf,Winforms,Combobox,Datatable,有人能帮我设置数据表中的combobox或combobox编辑值吗? 在WinForms中是这样的: DataSet dataBases = GetDatabases(); if ((dataBases != null) && (dataBases.Tables[0].Rows.Count > 0)) { comboBoxDataBases.DisplayMember = "DbName"; comboBoxDataBases.DataSource = d
DataSet dataBases = GetDatabases();
if ((dataBases != null) && (dataBases.Tables[0].Rows.Count > 0))
{
comboBoxDataBases.DisplayMember = "DbName";
comboBoxDataBases.DataSource = dataBases.Tables[0];
if (comboBoxDataBases.FindStringExact(tempDBName) > 0)
{
comboBoxDataBases.SelectedIndex = comboBoxDataBases.FindStringExact(tempDBName);
}
}
else
{
comboBoxDataBases.DataSource = null;
}
如何使用WPF实现相同的功能
任何人都可以发布一些简单的例子。提前谢谢。以下是如何在WPF中实现这一点:
<ComboBox
ItemsSource="{Binding DbTable}" <!-- Get the data from the DataContext -->
SelectedValuePath="{Binding DbName}" <!-- Only desirable if you want to select string values, not table rows -->
SelectedValue="{Binding tempDBName, Mode=OneWay}" > <!-- Initialize value -->
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding DbName}" /> <!-- Display the DbName in the dropdown -->
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
此外,您可以考虑从上面的XAML中删除Mode=OneWay
,并允许对组合框的更改更新“tempDbName”属性。一般来说,这会导致更干净的实现
this.DataContext = new
{
DbTable = dataBases.Tables[0],
...
};