我在ResourceDictionary中有一个MergedDictionaries和DateTemplate,一切都很好,直到我添加了一个转换器:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WPFTry"> <local:IsEnabledConverter x:Key="isEnabled"/> <===== causes problem <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Styles.xaml" /> </ResourceDictionary.MergedDictionaries> <DataTemplate x:Key="fileinfoTemplate" DataType="{x:Type local:MyFileInfo}"> ... template stuff </DataTemplate> </ResourceDictionary>
添加Converter行会导致DataTemplate行出现此错误:
Property elements cannot be in the middle of an element's content. They must be before or after the content.
为什么会导致此错误?
请注意,如果我注释掉MergedDictionaries,代码将编译并且Converter工作正常.
解决方法
该错误告诉您问题:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WPFTry"> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Styles.xaml" /> </ResourceDictionary.MergedDictionaries> <!-- Move this here --> <local:IsEnabledConverter x:Key="isEnabled"/> <DataTemplate x:Key="fileinfoTemplate" DataType="{x:Type local:MyFileInfo}"> ... template stuff </DataTemplate> </ResourceDictionary>
您正在尝试在资源字典上设置属性之前放置内容.错误说“属性元素”(例如ResourceDictionary.MergedDictionaries)不能位于元素“content”的中间(例如你的datatemplate / converter等)
任何有点的东西.必须出现在元素的顶部,因为您实际上是在XAML中设置属性.任何没有的东西.是内容,必须出现在任何属性设置者下面.