开发者

Why are XML DataTemplates ignored?

开发者 https://www.devze.com 2023-02-05 23:16 出处:网络
In the following sample, the DataTemplate is ignored by WPF. Why is this? <Window x:Class=\"TestXmlNonBinding.MainWindow\"

In the following sample, the DataTemplate is ignored by WPF.

Why is this?

<Window x:Class="TestXmlNonBinding.MainWindow"
    xmlns="http://sche开发者_StackOverflowmas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Xml="clr-namespace:System.Xml;assembly=System.Xml">
<Window.Resources>
    <DataTemplate DataType="{x:Type Xml:XmlDocument}">
        <TextBlock>Hello</TextBlock>
    </DataTemplate>
</Window.Resources>
<Window.DataContext>
    <Xml:XmlDocument></Xml:XmlDocument>
</Window.DataContext>
<Grid>
    <ContentControl Content="{Binding}"></ContentControl>
</Grid>


I believe the issue is with binding, not template selection.

If you look at the documentation for Binding.XPath, you'll see that when the binding source is XML data (i.e. an XmlDocument or XmlNode) the XPath property is used, rather than the Path property, to find the property on the data source.

I suspect that what's happening here is that the Binding is not returning an XmlDocument. The binding sees that the source object is an XmlDocument, and it calls SelectNodes on it, passing in the value of the XPath property as an argument. That's null (or maybe an empty string), and so SelectNodes doesn't return anything.


DataTemplates have a special functionality to deal with XML, if there is XML-data the DataType is interpreted as the name of the XML-element that should be templated:

If the template is intended for object data, this property contains the type name of the data object (as a string). To refer to the type name of the class, use the x:Type Markup Extension. If the template is intended for XML data, this property contains the XML element name. See the documentation remarks for details about specifying a non-default namespace for the XML element.

0

精彩评论

暂无评论...
验证码 换一张
取 消