wpf使用DataTemplate进入HierachicalDataTemplate

时间:2014-04-07 14:18:50

标签: c# wpf xaml treeview hierarchicaldatatemplate

在Wpf应用程序中我将相同的项集合显示到ListBox和TreeView中,List仅显示第一级,TreeView显示整个Hierarchical。我的问题是:为什么在TreeView中没有应用我为Item对象声明的DataTemplate?我如何在两个控件之间共享相同的DataTemplate(文本的颜色必须是红色)?

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

    <Grid.Resources>
        <DataTemplate DataType="{x:Type viewmodel:Item}">
            <TextBlock Foreground="Red" Text="{Binding Caption}"></TextBlock>
        </DataTemplate>
    </Grid.Resources>
    <ListBox Grid.Row="0" Name="lb1" ></ListBox>
    <TreeView Name="tv1"  Grid.Row="1" >
        <TreeView.Resources>
            <HierarchicalDataTemplate DataType="{x:Type viewmodel:Item}" ItemsSource="{Binding Items}" >

            </HierarchicalDataTemplate>
        </TreeView.Resources>
    </TreeView>
</Grid>

MainWindow.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TestWpf
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{

    public MainWindow()
    {
        InitializeComponent();

        ObservableCollection<Item> Items = new ObservableCollection<Item>();

        var item1 = new Item("1");
        Items.Add(item1);

        item1.Items.Add(new Item("1.1"));
        item1.Items.Add(new Item("1.2"));
        item1.Items.Add(new Item("1.3"));

        var item2 = new Item("2");
        Items.Add(item2);

        item2.Items.Add(new Item("2.1"));
        item2.Items.Add(new Item("2.2"));
        item2.Items.Add(new Item("2.3"));

            var item3 = new Item("3");
            Items.Add(item3);

            item3.Items.Add(new Item("3.1"));
            item3.Items.Add(new Item("3.2"));
            item3.Items.Add(new Item("3.3"));

            this.lb1.ItemsSource = Items;
            this.tv1.ItemsSource = Items;
        }
    }
}

Item.cs

namespace TestWpf
{
    public class Item
    {
        public List<Item> Items { get; set; }
        public string Caption { get; set; }
        public Item(string caption)
        {
            this.Caption = caption;
            this.Items = new List<Item>();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我只是在VS中复制并粘贴你的代码,按下F5就可以了。 我唯一需要更改的是命名空间,因为我使用WPFApplication1创建了它:)

尝试将您的代码带到一个新项目并尝试构建它并查看它是否有效。