如何在WPF DataTemplate上使用DataType属性?

编程入门 行业动态 更新时间:2024-10-21 09:08:45
本文介绍了如何在WPF DataTemplate上使用DataType属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

因此,显然我在做错事,但是使用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属性?

本文发布于:2023-11-07 05:33:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565677.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   如何在   DataTemplate   WPF   DataType

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!