【问题标题】:How to bind ComboBox or ComboboxEdit to a DataTable如何将 ComboBox 或 ComboboxEdit 绑定到 DataTable
【发布时间】:2010-12-16 23:34:02
【问题描述】:

谁能帮我从数据表中设置组合框或组合框编辑值? 在 WinForms 中是这样的:

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 winforms combobox datatable


    【解决方案1】:

    以下是在 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,并让对 ComboBox 的更改更新您的“tempDbName”属性。一般来说,这会导致更简洁的实现。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-19
      • 1970-01-01
      • 2015-11-29
      • 2018-02-11
      • 2019-06-08
      • 2017-01-07
      • 1970-01-01
      • 2011-10-12
      相关资源
      最近更新 更多