根据MSDN,Silverlight静态资源查找机制应该:
StaticResource的查找行为从应用实际使用的对象以及它自己的Resources属性开始。(...)然后,查找序列检查下一个对象树的父对象。(...)否则,查找行为将提升到下一个父级,指向对象树根,等等。
这很简单,因为它缩小到简单地遍历对象图,直到找到请求的资源键。因此,人们可能会认为,这样做是可行的:
<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。
我是不是遗漏了一些显而易见的东西,或者文档是不正确的?
发布于 2011-12-02 11:11:00
这是因为在将子UserControl插入母UserControl之前,必须完全实例化它,而且由于它还不知道它的父UserControl,所以它不知道SolidColorBrush。
如果将SolidColorBrush放在Appl.xaml的参考资料部分,它就会正常工作: App.xaml是在应用程序启动时加载的,您输入的任何资源都是全局可用的。
尽管如此,您还可以在子InnerTextForeground UserControl中公开一个SolidColorBrush依赖项属性,并将其设置为父UserControl中的本地SolidColorBrush资源。
这不是很难,但是如果你有困难请告诉我。
https://stackoverflow.com/questions/8355406
复制相似问题