2017-03-07 8 views
1

実行時に静的リソースを使用してボタンのスタイルを設定するにはどうすればよいですか? Background="{StaticResource OrangeGradient}"は、実行時にC#でどのように見えるのかを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" > 

:XAMLは、このようになりますか?

マイリソースディクショナリ、リソース/ 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で、対象のブラシは(WindowまたはUserControl)です。

+0

私の 'App.xaml'ファイル内のリソース辞書にはどうやってアクセスできますか? –

+0

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

+0

Wonderful、ありがとうございます。 –

関連する問題