2016-04-13 33 views
0

我有幾個StackPanels在我的應用程序,它希望自己的孩子申請某些風格:WPF自動將樣式分配給孩子

<StackPanel.Resources> 
    <Style TargetType="TextBlock" BasedOn="{StaticResource SettingLabel}" /> 
    <Style TargetType="DockPanel" BasedOn="{StaticResource SettingRow}" /> 
    <Style TargetType="CheckBox" BasedOn="{StaticResource SettingCheckBox}" /> 
    <Style TargetType="PasswordBox" BasedOn="{StaticResource DialogPasswordBox}" /> 
    <Style TargetType="TextBox" BasedOn="{StaticResource DialogTextBox}" /> 
</StackPanel.Resources> 

相反,雖然給予一遍又一遍寫這5條線我的StackPanel本身就是一種可應用這些技術的風格,因此可以減少冗餘。

這是不可能的設置Resources的風格二傳手,因爲它沒有依賴項屬性:

<Style x:Key="SettingPanel" TargetType="StackPanel"> 
    <Setter Property="Resources"> 
     <Setter.Value> 
      <Style TargetType="TextBlock" BasedOn="{StaticResource SettingLabel}" /> 
      <Style TargetType="DockPanel" BasedOn="{StaticResource SettingRow}" /> 
      <Style TargetType="CheckBox" BasedOn="{StaticResource SettingCheckBox}" /> 
      <Style TargetType="PasswordBox" BasedOn="{StaticResource DialogPasswordBox}" /> 
      <Style TargetType="TextBox" BasedOn="{StaticResource DialogTextBox}" /> 
     </Setter.Value> 
    </Setter> 
</Style> 

那麼,有沒有其他辦法做到這一點,而不必設置在每一個孩子的樣式和重複作業風格?

回答

3

您可以在StackPanelStyle.Resources中定義樣式。這些將使用SettingPanel作爲樣式應用於StackPanel的所有孩子。

<Style x:Key="SettingPanel" TargetType="StackPanel"> 
    <Style.Resources> 
      <Style TargetType="TextBlock" BasedOn="{StaticResource SettingLabel}" /> 
      <Style TargetType="DockPanel" BasedOn="{StaticResource SettingRow}" /> 
      <Style TargetType="CheckBox" BasedOn="{StaticResource SettingCheckBox}" /> 
      <Style TargetType="PasswordBox" BasedOn="{StaticResource DialogPasswordBox}" /> 
      <Style TargetType="TextBox" BasedOn="{StaticResource DialogTextBox}" /> 
    </Style.Resources> 
</Style> 
相關問題