2017-03-07 61 views
1

如何在運行時使用靜態資源設置按鈕的樣式? xaml看起來像這樣:WPF在運行時設置靜態資源

<Button Grid.Column="0" Grid.Row="2" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Margin="1,0,1,0" 
        Background="{StaticResource OrangeGradient}" FontFamily="Lucida Sans" BorderBrush="Black" > 

在運行時,Background="{StaticResource OrangeGradient}"看起來像什麼?

我的資源字典,資源/ Styles.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
       xmlns:local="clr-namespace:myProj"> 

<LinearGradientBrush x:Key="OrangeGradient" EndPoint="0.5,1" StartPoint="0.5,0"> 
     <LinearGradientBrush.RelativeTransform> 
      <TransformGroup> 
       <ScaleTransform CenterY="0.5" CenterX="0.5"/> 
       <SkewTransform CenterY="0.5" CenterX="0.5"/> 
       <RotateTransform Angle="270" CenterY="0.5" CenterX="0.5"/> 
       <TranslateTransform/> 
      </TransformGroup> 
     </LinearGradientBrush.RelativeTransform> 
     <GradientStop Color="#FFE08A19" Offset="0"/> 
     <GradientStop Color="#FFF5CA86" Offset="1"/> 
    </LinearGradientBrush> 

的App.xaml:

<Application x:Class="myProj.App" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:local="clr-namespace:myProj" 
      StartupUri="MainWindow.xaml"> 

    <Application.Resources> 

     <ResourceDictionary> 
      <ResourceDictionary.MergedDictionaries> 
       <ResourceDictionary Source="Resources/Styles.xaml" /> 
      </ResourceDictionary.MergedDictionaries> 
     </ResourceDictionary> 

    </Application.Resources> 

</Application> 
+0

StaticResource不能在運行時更改,請改用DynamicResource! – Fruchtzwerg

+0

只是爲了澄清,我不想更改資源定義,只是將其應用於按鈕 –

回答

2

設置Background靜態資源的模擬,但在運行時只是:

yourButton.Background = (Brush)this.Resources["OrangeGradient"]; 

其中ResourcesResourceDictionary與目標畫筆,例如您的WindowUserControl的根ResourceDictionary

+0

如何訪問我的App.xaml文件中的資源字典? –

+0

@PatrickSchomburg使用'System.Windows.Application.Current.Resources' – Evk

+0

精彩,謝謝。 –