Treeview数据绑定到DataTable

时间:2010-01-07 23:52:28

标签: c# wpf xaml data-binding treeview

我是WPF的新手,非常感谢我在努力解决的问题上提供帮助。我需要在主应用程序菜单中的WPF TreeViewItem中绑定TreeView。我需要的是将单个数据表绑定到TreeViewItem(XAML和代码隐藏)的正确语法,这是我到目前为止所拥有的。请提供您的建议代码,感谢您的帮助。为了使事情再次清楚,我只是想绑定ItemList TreeViewItem的{​​{1}}。 ItemsSource显示表格中的5行,但它显示TreeView而非实际值,您的帮助表示赞赏

XAML

System.Data.DataRow

C#

<Window x:Class="WPFToolkit.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WPFToolkit"
        Title="Window1" Height="300" Width="300">
  <Window.Resources>
  </Window.Resources>
  <Grid>
    <TreeView Name="SampleTree" Margin="-9,0,0,0">
      <TreeViewItem Header="Create List" MouseDoubleClick="CreateCodeset_Click" 
                    IsEnabled="True"/>
      <TreeViewItem Header="Search List" MouseDoubleClick="SearchCodeSet_Click"/>
      <TreeViewItem Header="List Items" Margin="15,0,0,0">
        <TreeViewItem Name="ItemList" Header="Codeset 1" 
                      Style="{StaticResource listMenuItem}">
        </TreeViewItem>
      </TreeViewItem>
    </TreeView>
  </Grid>
</Window>

1 个答案:

答案 0 :(得分:1)

我对你的xaml和CreateList进行了一些更改,请检查它是否适合你

xaml :我删除了Style =“..”并将ItemTemplate设置为窗口资源部分中定义的datatemplate。 TextBlock将弯曲到数据集的“名称”字段

<Window.Resources>
    <DataTemplate x:Key="itemsTemplate">
        <StackPanel>
            <TextBlock Text="{Binding Path=Name}"/>
        </StackPanel>
    </DataTemplate>
</Window.Resources>

<Grid>
    <TreeView Height="277" HorizontalAlignment="Left" 
              Margin="64,24,0,0" Name="treeView1" 
              VerticalAlignment="Top" Width="268">
        <TreeViewItem Header="Create List" IsEnabled="True"/>
        <TreeViewItem Header="Search List" />
        <TreeViewItem Header="List Items" Margin="15,0,0,0" IsExpanded="true">
            <TreeViewItem Name="ItemList" Header="Codeset 1" IsExpanded="true"                               
                          ItemTemplate="{StaticResource itemsTemplate}"/>
        </TreeViewItem>
    </TreeView>
</Grid>

CreateList :我已将ItemList.ItemsSource更改为DataView对象;您还将“Name”项分配给同一行对象,看起来像示例代码中的错误。

DataTable tbl = new DataTable("Items");
tbl.Columns.Add("Name");

DataRow row = tbl.NewRow();
row["Name"] = "Fruits";
tbl.Rows.Add(row);

DataRow row2 = tbl.NewRow();
row2["Name"] = "Vegetables"; // original code has "row" here
tbl.Rows.Add(row2);

DataRow row3 = tbl.NewRow();
row3["Name"] = "Meats";
tbl.Rows.Add(row3);

DataRow row4 = tbl.NewRow();
row4["Name"] = "Drinks";
tbl.Rows.Add(row4);

DataRow row5 = tbl.NewRow();
row5["Name"] = "Bread";
tbl.Rows.Add(row5);

//ItemList.ItemsSource = tbl.Select();
ItemList.ItemsSource = new DataView(tbl);

希望这有帮助,尊重