2011-12-02 123 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資源。
這不是很難,但讓我知道如果你有麻煩這樣做。