2017-04-09 34 views
1

改變全球的風格我有以下風格的ResourceDictionary文件WPF - 從代碼

<Color x:Key="LightCyan">LightCyan</Color> 
<SolidColorBrush x:Key="LightCyanBrush" Color="{StaticResource LightCyan}" /> 

<Style x:Key="TextBoxStyle" TargetType="TextBox"> 
    <Setter Property="Width" Value="150" /> 
    <Setter Property="Margin" Value="0,0,0,3" /> 
</Style> 

<Style TargetType="TextBox" BasedOn="{StaticResource TextBoxStyle}"> 
    <Style.Triggers> 
     <Trigger Property="IsReadOnly" Value="False"> 
      <!-- Change brush color at run time --> 
      <Setter Property="Background" Value="{StaticResource LightCyanBrush}" /> 
     </Trigger> 
    </Style.Triggers> 
</Style> 

我需要改變文本框的背景顏色時IsReadOnly = False在運行時,從顏色的十六進制代碼。

回答

1

最簡單方法是使用DynamicResource而不是StaticResource,例如:

<Window.Resources> 
    <SolidColorBrush x:Key="TextBoxEditableBackgroundBrush" 
        Color="LightCyan" /> 
    <Style x:Key="TextBoxStyle" 
      TargetType="TextBox"> 
     <Setter Property="Width" 
       Value="150" /> 
     <Setter Property="Margin" 
       Value="0,0,0,3" /> 
    </Style> 
    <Style TargetType="TextBox" 
      BasedOn="{StaticResource TextBoxStyle}"> 
     <Style.Triggers> 
      <Trigger Property="IsReadOnly" 
        Value="False"> 
       <!-- Change brush color at run time --> 
       <Setter Property="Background" 
         Value="{DynamicResource TextBoxEditableBackgroundBrush}" /> <!-- note here --> 
      </Trigger> 
     </Style.Triggers> 
    </Style> 
</Window.Resources> 

然後在代碼中你只需要改變你的畫筆:

var brush = new SolidColorBrush(Colors.Red); 
brush.Freeze(); 
this.Resources["TextBoxEditableBackgroundBrush"] = brush;