2013-06-26 35 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