2011-12-02 125 views
0

According to MSDN,Silverlight的静态资源查找机制应该:静态资源查找

与在实际使用的应用对象和自身的资源属性开始的StaticResource的查找行为。 (...)查找序列然后检查下一个对象树父项。 (...)否则,查找行为前进到对象树根的下一个父级别,依此类推。

这很简单,因为它缩小到只是遍历对象图形,直到找到请求的资源键。有人可能会认为,这会起作用:

<UserControl x:Class="ResourcesExample.MainPage" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:ResourcesExample="clr-namespace:ResourcesExample" 
    mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400"> 
    <UserControl.Resources> 
    <SolidColorBrush Color="Green" x:Key="GreenBrush"/> 
    </UserControl.Resources> 
    <Grid x:Name="LayoutRoot"> 
    <ResourcesExample:Tester /> 
    </Grid> 
</UserControl> 

<UserControl x:Class="ResourcesExample.Tester" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400"> 
    <Grid x:Name="LayoutRoot"> 
    <TextBlock Text="Show green!" Foreground="{StaticResource GreenBrush}"/> 
    </Grid> 
</UserControl> 

那么它不会。我得到的是XamlParseException : Cannot find a Resource with the Name/Key GreenBrush

我是否在此处丢失了明显的东西或文档不正确?

回答

1

这是因为在将UserControl插入母UserControl之前,它必须完全实例化,并且因为它尚不知道它的父项,所以它不知道SolidColorBrush。

如果你把的SolidColorBrush在Appl.xaml的参考资料部分,它将工作:App.xaml中的应用程序在启动时加载,和你把任何资源会有全局可用。也就是说,您也可以在子UserControl中公开一个InnerTextForeground Dependency Property,并将其设置为您的本地UserControl中的SolidColorBrush资源。
这不是很难,但让我知道如果你有麻烦这样做。