隐藏已在父子层次结构中显示的TreeView项

时间:2014-08-11 15:14:06

标签: c# .net wpf

我试图在TreeView中显示具有自我父亲关系的DataTable的内容。问题是存在具有祖先的DataTable记录的重复:它们显示为父项和层次结构的成员:

TreeView

我想只显示一次项目:在层次结构中。

Window xaml:

<Window x:Class="BindingTreeViewToDataSet.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:BindingTreeViewToDataSet"
    Title="MainWindow" Height="350" Width="525">

<Window.Resources>
    <ObjectDataProvider x:Key="DataSetProvider" MethodName="CreateDataSet" ObjectType="{x:Type local:DataSetCreator}" />
</Window.Resources>

<Grid>
    <TreeView Grid.Row="0" DataContext="{StaticResource DataSetProvider}" ItemsSource="{Binding Data}">
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding Parent2Child}" >
                <TextBlock Text="{Binding Name}" />
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>
</Grid>
</Window>

数据集:

public static class DataSetCreator
{
    public static DataSet CreateDataSet()
    {
        var ds = new DataSet();

        var tbl = new DataTable("Data");
        tbl.Columns.Add("ID", typeof(int));
        tbl.Columns.Add("ParentID", typeof(int));
        tbl.Columns.Add("Name");

        ds.Tables.Add(tbl);
        ds.Relations.Add("Parent2Child", tbl.Columns["ID"], tbl.Columns["ParentID"]);

        tbl.Rows.Add(new object[] { 0, DBNull.Value, "Parent#1" });
        tbl.Rows.Add(new object[] { 1, 0, "Child#2" });
        tbl.Rows.Add(new object[] { 2, 1, "Subchild#3" });

        return ds;
    }
}

1 个答案:

答案 0 :(得分:0)

我已经改变了方法和过滤数据源,如此处所述[{3}}

谢谢你,@谢里丹:)