5

How can I set the style of a button at runtime using a static resource? The xaml looks like this:

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

What would the Background="{StaticResource OrangeGradient}" look like in c# at runtime?

My Resource dictionary, Resources/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> 
2
  • StaticResource can not be changed at runtime, use DynamicResource instead! Commented Mar 7, 2017 at 14:58
  • Just to clarify, I don't want to change the resource definition, just apply it to the button Commented Mar 7, 2017 at 15:10

1 Answer 1

3

Analog of setting Background to static resource, but at runtime is just:

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

Where Resources is ResourceDictionary with target brush, for example root ResourceDictionary of your Window or UserControl.

Sign up to request clarification or add additional context in comments.

2 Comments

How can I access a resource dictionary in my App.xaml file?
@PatrickSchomburg using System.Windows.Application.Current.Resources

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.