2010-01-20 60 views
12

我需要使用資源來設置WPF應用程序中主窗口的顏色。由於資源聲明出現在窗口聲明(我正在導入資源字典)之後,因此我無法在Window對象中使用Background屬性。所以,我認爲我會這樣設置背景:使用資源設置窗口背景顏色

<Window.Resources> 
... 
</Window.Resources> 

<Window.Background> 
    <SolidColorBrush Color="{StaticResource WindowBackgroundBrush}" /> 
</Window.Background> 

我的語法有點偏差,因爲對象不會爲其Color屬性使用畫筆資源。什麼是修復?謝謝你的幫助。

回答

15

試試這個

<Window.Background> 
    <StaticResource ResourceKey="WindowBackgroundBrush" /> 
</Window.Background> 
0

解決方法是將資源放入App.xaml中。這樣你就可以在你的窗口上設置背景而沒有任何問題。

+0

一個解決方案,但不是解決方案。對於涉及多個項目的應用程序(如Prism應用程序)來說這不太合適。 – 2010-01-20 14:58:48

16

這個工程:

<Window x:Class="Moria.Net.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" 
     x:Name="window" 
     Background="{DynamicResource WindowBrush}" 
     Width="800" Height="600"> 
    <Window.Resources> 
     <SolidColorBrush x:Key="WindowBrush" Color="LightGray"/> 
    </Window.Resources> 
</Window> 

這裏要注意的主要事情是x:名稱窗口,並在後臺財產

alternativly的DynamicResource ,這也適用於......

<Window.Resources> 
     <SolidColorBrush x:Key="WindowBrush" Color="LightGray"/> 
    </Window.Resources> 
    <Window.Style> 
     <Style TargetType="{x:Type Window}"> 
      <Setter Property="Background" Value="{StaticResource WindowBrush}"/> 
     </Style> 
    </Window.Style> 

作爲一個方面,如果你想使用主題爲你的應用程序,你應該看看component resource keys