Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

c# - How do I use the DataType property on a WPF DataTemplate?

So obviously I am doing something wrong, but I just cannot seem to get the HierarchicalDataTemplate (or even just DataTemplate) to work when using the DataType property. I have created the shortest possible WPF application to demonstrate the problem.

XAML:

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:System="clr-namespace:System;assembly=mscorlib"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="Window1" Height="300" Width="300" Loaded="Window_Loaded">
    <Window.Resources>
        <HierarchicalDataTemplate DataType="x:Type local:Foo">
            <TextBlock Text="I am a Foo" />
        </HierarchicalDataTemplate>
        <HierarchicalDataTemplate DataType="x:Type System:String">
            <TextBlock Text="I am a String" />
        </HierarchicalDataTemplate>
    </Window.Resources>
    <Grid>
        <TreeView Name="treeView1" ItemsSource="{Binding}" />
    </Grid>
</Window>

CODE:

namespace WpfApplication1
{
    public class Foo
    {
        public string Name { get; set; }
    }

    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var list = new List<object> { "a", 1, "b", 2, new Foo() { Name="Brian"}};
            treeView1.DataContext = list;
        }
    }
}

Obviously I am expecting it display the following in the treeview.

I am a string
1
I am a string
2
I am a foo

But my application actually displays the following.

a
1
b
2
WpfApplication1.Foo

The strange thing is that almost every example I see on the web does this very thing (with slight variations) and no one else seems to be having a problem with it. Yet I have tried countless different ways of rearranging the XAML and nothing seems to help. I am hoping another pair eyes can help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your code is fine, but your DataType attribute values need to be wrapped in curly braces:

<HierarchicalDataTemplate DataType="{x:Type local:Foo}">
    <TextBlock Text="I am a Foo" />
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type System:String}">
    <TextBlock Text="I am a String" />
</HierarchicalDataTemplate>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...