What is the scope of StaticResource within a WPF ResourceDictionary?

那年仲夏 提交于 2019-12-21 07:34:08

问题


I have a WPF ResourceDictionary with the following TextBlock:

<TextBlock Visibility="{Binding Converter={StaticResource MyBoolProp ResourceKey=BoolToVis}}">
</TextBlock>

The ResourceDictionary is included in App.xaml under MergedDictionaries:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="MyResourceDictionary.xaml"/>

Within the App.xaml I have defined the BoolToVis converter (again, under Application.Resources)

<BooleanToVisibilityConverter x:Key="BoolToVis" />

When I start my app up - I get the following XamlParseException:

"Provide value on 'System.Windows.Markup.StaticResourceHolder' threw an exception."

The InnerException is:

"Cannot find resource named 'BoolToVis'. Resource names are case sensitive."

I'm able to refer to this converter directly with App.xaml (in fact, the particular XAML declaration is identical) and within other UserControls with no problems.

This particular bit of code also worked fine under the .NET 4.0 RC (and Beta2). This error only started happening when I upgraded to the .NET 4.0 RTM.

I'm able to work around it by declaring another BooleanToVisibilityConverter within MyResourceDictionary.xaml and referring to it like so:

<TextBlock Visibility="{Binding Converter={StaticResource MyBoolProp ResourceKey=BoolToVis2}}">
</TextBlock>

Any reason why I should need to do this?


回答1:


Per MSDN:

Resources in a merged dictionary occupy a location in the resource lookup scope that is just after the scope of the main resource dictionary they are merged into.

Resources defined in App.xaml cannot be seen by a merged ResourceDictionary. I would think it makes more sense to define a converter used in a ResourceDictionary in the ResourceDictionary itself, or another ResourceDictionary which houses all your converters.



来源:https://stackoverflow.com/questions/2678893/what-is-the-scope-of-staticresource-within-a-wpf-resourcedictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!