因此,显然我在做错事,但是使用DataType属性时,似乎似乎无法使HierarchicalDataTemplate(甚至只是DataTemplate)正常工作.我创建了尽可能最短的WPF应用程序来演示该问题.
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="schemas.microsoft/winfx/2006/xaml/presentation" xmlns:x="schemas.microsoft/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>代码:
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奇怪的是,我在网络上看到的几乎每个示例都做到了这一点(稍有变化),似乎没有其他人对此有问题.但是,我尝试了无数种重新排列XAML的不同方式,似乎没有任何帮助.我希望另一双眼睛可以提供帮助.
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.
推荐答案您的代码很好,但是您的DataType属性值需要用大括号括起来:
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>更多推荐
如何在WPF DataTemplate上使用DataType属性?
发布评论