2013-06-26 36 views
4

我知道this,这不适用于我的情况,和this,我不确定它是否可以适应。链接资源字典和StaticResource参考在根级别

我正在研究一个WPF控件库,而我没有一个App.xaml文件。我使用名为Styles.xml的文件来存储常用笔刷和其他资源。在我的用户控件的XAML文件中,我导入资源,然后尝试使用笔刷sBrush作为背景。

这个工程除了在根级别:

<UserControl x:Class="CMControls.TitledWindow" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300" 
      Background="{StaticResource ResourceKey=sBrush}"> <!--EXCEPTION!--> 

    <UserControl.Resources> 
     <ResourceDictionary> 
      <ResourceDictionary.MergedDictionaries> 
       <ResourceDictionary 
       Source="pack://application:,,,/CMControls;component/Styles.xaml"/> 
      </ResourceDictionary.MergedDictionaries> 
     </ResourceDictionary> 
    </UserControl.Resources> 

    <Canvas Background="{StaticResource ResourceKey=sBrush}" ... <!--Ok.--> 
... 

我相信这是因为,当根元素被实例化其子都没有,包括UserControl.Resources。有什么解决方法吗? 请注意,在设计师一切工作正常,无论我在哪里做参考

+0

您使用的是themes/generic.xaml吗? – JSJ

+0

不,我不是。感谢您的评论,我可以看一下,我不知道这一点。 – damix911

回答

4

更改UserControl资源合并后面的背景行,因为您必须在使用它们之前添加资源!

<UserControl x:Class="CMControls.TitledWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     mc:Ignorable="d" 
     d:DesignHeight="300" d:DesignWidth="300"> 

<UserControl.Resources> 
    <ResourceDictionary> 
     <ResourceDictionary.MergedDictionaries> 
      <ResourceDictionary 
      Source="pack://application:,,,/CMControls;component/Styles.xaml"/> 
     </ResourceDictionary.MergedDictionaries> 
    </ResourceDictionary> 
</UserControl.Resources> 
<UserControl.Background> <!--Set background here!--> 
    <StaticResource ResourceKey="sBrush"></StaticResource> 
</UserControl.Background> 
... 
+0

不错,谢谢你:-)我听说你可以使用元素和属性来设置相同的属性,但我不确定语法。 – damix911