2010-11-01 96 views
4

我正在構建一個WPF應用程序,並且我從標準WPF控件類型 - 文本塊,按鈕等等派生出了一堆控件。我嘗試添加一個資源字典到app.xaml來設置主題,但是我的自定義控件似乎沒有尊重它。 (例如,標準按鈕採用Aero主題就好了,但是從Button派生的myButton仍然是無形的。)有沒有一種方法可以將派生控件的主題設置爲與基本控件相同?WPF派生類和主題繼承?

編輯:我應該注意到這些自定義控件是在運行時實例化的,所以我不能直接通過XAML操作它們的屬性。我可以通過在應用程序資源字典中使用Setter來更改背景顏色等特定屬性,但尚未找到使用該技術設置主題的方法。

回答

1

如果你有這樣的風格在資源字典稱爲Dictionary1.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <Style x:Key="MyButtonStyle" 
      TargetType="{x:Type Button}" 
      BasedOn="{StaticResource {x:Type Button}}"> 
     <Setter Property="Width" Value="75" /> 
     <Setter Property="Height" Value="23" /> 
    </Style> 
</ResourceDictionary> 

然後你可以用後面

Uri resourceLocater = new Uri("/YourAssemblyName;component/Dictionary1.xaml", System.UriKind.Relative); 
ResourceDictionary resourceDictionary = (ResourceDictionary)Application.LoadComponent(resourceLocater); 
Style myButtonStyle = resourceDictionary["MyButtonStyle"] as Style; 

Button button = new Button(); 
button.Style = myButtonStyle; 
這段代碼設置上的任何按鈕