WPF在运行时设置静态资源

时间:2017-03-07 14:57:52

标签: c# wpf

如何使用静态资源在运行时设置按钮的样式? xaml看起来像这样:

zip

运行时c#中的<Button Grid.Column="0" Grid.Row="2" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Margin="1,0,1,0" Background="{StaticResource OrangeGradient}" FontFamily="Lucida Sans" BorderBrush="Black" > 会是什么样子?

我的资源字典,Resources / Styles.xaml:

Background="{StaticResource OrangeGradient}"

的App.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>

1 个答案:

答案 0 :(得分:2)

模拟将Background设置为静态资源,但在运行时只是:

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

使用目标画笔ResourcesResourceDictionary的位置,例如ResourceDictionaryWindow的根UserControl