如何在wpf中将数据表绑定到LISTBOX?

时间:2011-11-16 16:15:52

标签: c# wpf wpf-controls wpftoolkit

如何将数据表绑定到ListBox和

并选择一个我想在WPF中的ListBox中显示的字段。

你能帮忙谈谈这个话题吗?

感谢您的关注。

2 个答案:

答案 0 :(得分:3)

你可以尝试这个......

<Window x:Class="BindToAdoDataDemo.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
  <DockPanel>
    <Button Width="120" Height="30" Content="Add" Name="btn" DockPanel.Dock="Top"/>
    <ListBox ItemsSource="{Binding}" DisplayMemberPath="ChildItem"/>
  </DockPanel>
</Window>

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
        DataTable dataTable = MakeChildTable();
        this.DataContext = dataTable.Rows;
        this.btn.Click += delegate
        {
            DataRow row = dataTable.NewRow();
            row["childID"] = 50;
            row["ChildItem"] = "ChildItem " + 50;
            dataTable.Rows.Add(row);    
        };
    }

    private DataTable MakeChildTable()
    {
        DataTable table = new DataTable("childTable");
        DataColumn column;
        DataRow row;

        column = new DataColumn();
        column.DataType = System.Type.GetType("System.Int32");
        column.ColumnName = "ChildID";
        column.Caption = "ID";

        table.Columns.Add(column);

        column = new DataColumn();
        column.DataType = System.Type.GetType("System.String");
        column.ColumnName = "ChildItem";
        column.Caption = "ChildItem";
        table.Columns.Add(column);

        for (int i = 0; i <= 4; i++)
        {
            row = table.NewRow();
            row["childID"] = i;
            row["ChildItem"] = "Item " + i;
            table.Rows.Add(row);
        }

        return table;
    }
}

答案 1 :(得分:0)

这是一个纯XAML解决方案:

<DockPanel DataContext="{StaticResource myDataViewSource}">

    <ComboBox DockPanel.Dock="Bottom" x:Name="FieldSelector" SelectedIndex="0">
           <ComboBoxItem Content="Field1" Tag="Field1"/>
           <ComboBoxItem Content="Field2" Tag="Field2"/>
           <ComboBoxItem Content="Field3" Tag="Field3"/>
           <ComboBoxItem Content="Field4" Tag="Field4"/>
    </ComboBox>

    <ListBox ItemsSource="{Binding}"
             DisplayMemberPath="{Binding ElementName=FieldSelector,Path=SelectedItem.Tag}" />

</DockPanel>