2009-11-16 72 views
1

任何人都可以帮助我从数据表中设置combobox或combobox编辑值吗? 在的WinForms它是这样的:如何将ComboBox或ComboboxEdit绑定到DataTable

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做相同的功能?

任何人都可以发布一些简单的例子。提前感谢。

回答

0

这里是如何做到这一点的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> 

这是假设DataContext设置为一个对象包含表,这对于一个典型的WPF设计将被包含模板来完成,或者如果在顶层由代码:

this.DataContext = new 
{ 
    DbTable = dataBases.Tables[0], 
    ... 
}; 

此外,你可能会考虑从上面的XAML去除Mode=OneWay,让更改组合框更新“tempDbName”属性。一般来说,这会导致更清晰的实施。

相关问题