XAML XML DataBinding不起作用

时间:2014-07-26 13:33:02

标签: xml wpf xaml data-binding

我有一个类似于以下的XML文件:

<?xml version="1.0" encoding="utf-8" ?>
<Course
    Title="jQueryAjax"
    BtnAddisionalResourcesTitle=""
    BtnAddisionalResourcesAddress="">
<Topic
    Tag="ff"
    Title="">

    <Lesson
      Tag=""
      Title=""
      Address=""
    />

    <!--...-->


  </Topic>

  <!--...-->
</Course>

并且还有一个标签,如fallowing

    <Label 
                HorizontalAlignment="Right"
                VerticalAlignment="Top"
                FontSize="16pt"
                FontFamily="Myriad Pro"
                >
            <Label.Content>
                <Binding Source="{StaticResource CourseInfo}"
                         XPath="Title"
                         UpdateSourceTrigger="PropertyChanged"
                         />
            </Label.Content>
        </Label>

中间有一个XmlDataProvider

<Window.Resources>
    <XmlDataProvider x:Key="CourseInfo" Source="Settings\CourseScema.xml"/>
</Window.Resources>

但在使用System.Diagnostics.TextWriterTraceListener跟踪时出现此错误:

  

System.Windows.Data信息:41:BindingExpression路径错误:&#39;&#39;财产不是found for 'current item of collection' because data item is null. This could happen because the data provider has not produced any data yet. BindingExpression:Path=/; DataItem=null; target element is 'Label' (Name=''); target property is 'Content' (type 'Object')

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

首先,您需要向XPath提供根XmlDataProvider

<XmlDataProvider x:Key="CourseInfo" Source="Settings\CourseScema.xml" XPath="Course"/>

其次,Title是一个属性,因此您需要使用:

<Binding Source="{StaticResource CourseInfo}"
                         XPath="@Title"
                         UpdateSourceTrigger="PropertyChanged"
                         />

另外,请确保您的xml文件Build Action设置为ContentCopy to Output Directory设置为Copy alwaysCopy if newer