XAML DataTemplate无法访问App资源

时间:2016-01-31 08:19:02

标签: c# wpf xaml

烦人的XAML问题:我在资源字典文件中定义了一个DataTemplate,它必须访问在App.Resources中定义为资源的转换器。从逻辑上讲,我应该将我的DataTemplate字典与App.Resources字典合并,应该是它。但我得到一个例外,说我的转换器资源无法找到。我错过了什么吗?参考?定义顺序?

更新: 这是我的App.Resources

<ResourceDictionary>
    <!--Global Resources-->
    <BooleanToVisibilityConverter x:Key="BoolToVis"/>
    <!--System Resources-->
    <sys:Boolean x:Key="True">True</sys:Boolean>
    <sys:Boolean x:Key="False">False</sys:Boolean>
    <!--Framework Resources-->
    <fr:EnumToBoolConverter x:Key="EnumToBool"/>
    <fr:EnumAttributeConverter x:Key="EnumToAttr"/>
    <fr:FileInfoConverter x:Key="ToFileInfo"/>
    <fr:ImageInfoConverter x:Key="ToImageInfo"/>
    <fr:UnitConverter x:Key="ToUnit"/>
    <fr:CommandParameterConverter x:Key="ToCmdParam"/>
    <!--Style Resources-->
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="pack://application:,,,/FrameworkUI;component/Styles/Dark3DStyles.xaml"/>
        <ResourceDictionary Source="/Resources/DataTemplates.xaml/>
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

...这里是资源字典文件中定义的DataTemplate

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DataTemplate x:Key="NoteEnumTemplate">
    <Grid Height="22">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="22"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Image Grid.Column="0" Stretch="None"
               Source="{Binding Converter={StaticResource EnumToAttr},
                                ConverterParameter=ICON}">
            <Image.Effect>
                <DropShadowEffect ShadowDepth="0"/>
            </Image.Effect>
        </Image>
        <Label Grid.Column="1"
               Content="{Binding Converter={StaticResource EnumToAttr},
                                 ConverterParameter=DESCR}"/>
    </Grid>
</DataTemplate>

无法找到的转换器是EnumToAttr

1 个答案:

答案 0 :(得分:2)

您的问题是您定义资源/数据模板的顺序以及合并字典的顺序。

您正在将 ResourceDictionary 合并到App.Resources。所以 ResourceDictionary 是最重要的,必须要运行所有资源(密钥)。它不能使用派生的ResourceDictionary中定义的键。

ResourceDictionary 中移动转换器,然后查看结果。

你已经在最后编写了合并字典代码,但这样做不行。如果您看到在编译后将生成的代码的前景,则资源必须按上述顺序排列。

您设计前景的解决方案:

<ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="RD2.xaml"  />//Converter code
            <ResourceDictionary Source="RD.xaml"  /> //Template code            
</ResourceDictionary.MergedDictionaries>

以上代码将起作用,因为转换器代码始终会在模板代码之前生成。

相关问题