开发者

How to bind ComboBox or ComboboxEdit to a DataTable

could anyone help me to set combobox or combobox edit values from a datatable? In WinForms it was something like this:

DataSet dataBa开发者_StackOverflow中文版ses = 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;
}

How do I can do the same functionality with WPF?

Could anyone post some simple example.Thanks in advance.


Here's how to do it in 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>

This assumes DataContext is set to an object containing table, which for a typical WPF design would be done by the containing template, or if at top level by code:

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

Also, you might consider removing the Mode=OneWay from the XAML above and letting changes to the ComboBox update your "tempDbName" property. In general this results in a cleaner implementation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜