2016-07-28 30 views
0

我想將全局樣式應用於我的應用程序中的所有組合框。我通過在我的App.xaml文件中定義一個Style並指定一個TargetType來實現這一點,該類型應該將該樣式應用於所有指定類型的控件。但是,似乎我的風格根本沒有被應用。將全局樣式應用於組合框

這裏是我的代碼:

的App.xaml

<Application x:Class="Test.App" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:local="clr-namespace:Test" 
      StartupUri="MainWindow.xaml"> 
    <Application.Resources> 
     <ResourceDictionary> 
      <Style TargetType="{x:Type ComboBox}"> 
       <Setter Property="Background" Value="Red"></Setter> 
      </Style> 
     </ResourceDictionary> 
    </Application.Resources> 
</Application> 

MainWindow.xaml

<Window x:Class="Test.MainWindow" 
     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:local="clr-namespace:Test" 
     mc:Ignorable="d" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <ComboBox Margin="173,130,186,166"></ComboBox> 
    </Grid> 
</Window> 

我沒有任何代碼隱藏在這一點上比其他VS爲WPF表單生成的默認代碼。

我希望這個XAML代碼可以將任何窗口中任何ComboBox的背景改爲紅色,而無需爲每個ComboBox手動指定樣式。 (我真的不想爲每個ComboBox手動寫出來 - 我的應用程序最終會使用很多很多的CB,這將是一個主要的痛苦 - 不要說它看起來很混亂。)

我試圖模擬我的this question之後的代碼,但沒有得到任何結果。

回答

0

嘗試避免App.Xaml中嵌套的ResourceDictionary。 修復這樣:

<Application.Resources> 
    <Style TargetType="{x:Type ComboBox}"> 
     <Setter Property="Background" Value="Red"></Setter> 
    </Style> 
</Application.Resources> 
+0

感謝您的回答。不幸的是,在我刪除''標籤後,它似乎沒有任何不同之處。 –

0

我建議創建解決方案中的一個文件夾,並在裏面添加的XAML控制:ResourceDictionary,你要定義你想默認情況下應用於所有的全局樣式。

例如:

<ResourceDictionary  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <Style TargetType="{x:Type TextBox}"> 
     <Setter Property="Height" Value="25"/> 
     <Setter Property="Background" Value="red"></Setter> 
    </Style> 
</ResourceDictionary> 

現在,你只需要放一個參考,你的App.xaml像這樣:

<Application.Resources> 
    <ResourceDictionary> 
     <ResourceDictionary.MergedDictionaries> 
      <ResourceDictionary Source="/Views/Style/GlobalStyle.xaml"/> 
     </ResourceDictionary.MergedDictionaries> 
    </ResourceDictionary> 
</Application.Resources> 

希望它會幫助你。

祝您有美好的一天。