DataTemplate隐式映射到System.Xml.XmlDocument未被识别。

3

我正在尝试创建自己的控件来查看XmlDocuments。

我对WPF的理解是,我可以创建一个DataTemplate,它会隐式地映射到某个类型。

然后,如果我将此类型的对象分配给ContentPresenter,它将自动选择适当的DataTemplate。

那么为什么这段15行的XAML代码没有起作用呢?

<Window x:Class="TestDataTemplates.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:systemXml="clr-namespace:System.Xml;assembly=System.Xml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <DataTemplate DataType="{x:Type systemXml:XmlDocument}"> 
            <TextBlock Text="Look! An xml document!" />
        </DataTemplate>
        <systemXml:XmlDocument x:Key="TokenXmlDocument" />
    </Window.Resources>
    <Grid>
        <ContentPresenter Content="{StaticResource ResourceKey=TokenXmlDocument}"  />
    </Grid>
</Window>

ContentPresenter的内容是XmlDocument,因此应该使用我为其创建的数据模板。我应该看到文本“Look! An xml document!”。

但是我看到一个空窗口。


稍后编辑:有人在这里遇到了类似的问题:为什么忽略XML数据模板?

3个回答

1

奇怪!真的。

而且这个有效!

<Window x:Class="WpfApplication1.Window2"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    xmlns:sysxml="clr-namespace:System.Xml;assembly=System.Xml"
    Title="Window2" Height="350" Width="525">
  <Window.Resources>
     <DataTemplate DataType="{x:Type sysxml:XmlDocument}">
        <TextBlock Text="Look! A system Xml!" />
     </DataTemplate>
     <local:LocalXmlDocument x:Key="LocalXmlDocument" />
  </Window.Resources>
  <StackPanel x:Name="Panel">
     <ContentPresenter Content="{StaticResource LocalXmlDocument}"  />
  </StackPanel>
</Window>

而在代码后台...

public class LocalXmlDocument : XmlDocument
{
}

WPF的奇妙且难以解释的世界!


1
不知道?人们只是不够勤快地去查找资料 - H.B.

0

F1:

如果模板用于对象数据,则此属性包含数据对象的类型名称(作为字符串)。要引用类的类型名称,请使用x:Type标记扩展。如果模板用于XML数据,则此属性包含XML元素名称。有关指定XML元素的非默认命名空间的详细信息,请参阅文档注释。


0

不要使用"{x:Type sysxml:XmlDocument}",而是使用"#document"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接