如何从资源字典中获取画笔并在wpf中动态地将其应用于元素?

时间:2012-08-28 04:33:20

标签: c# wpf resourcedictionary

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<LinearGradientBrush x:Key="ButtonNormalBackgroundBrush" EndPoint="0.5,1" StartPoint="0.5,0">
    <GradientStop Color="#C10099FF" Offset="0"/>
    <GradientStop Color="#C16699CC" Offset="1"/>
    <GradientStop Color="#C1006699" Offset="0.49"/>
</LinearGradientBrush>
<ResourceDictionary/>

现在我想从ResourceDictonary获取LinearGradientBrush并将其动态应用于按钮作为wpf中的背景颜色。

 BtnGetBrushes.Background = Brushes.Green;

我想应用上面的颜色而不是这个(Brushes.Green)。我该怎么做?

2 个答案:

答案 0 :(得分:17)

假设您的ResourceDictionary在上下文中可用:

<Button Background="{DynamicResource ResourceKey=ButtonNormalBackgroundBrush}" />

或代码

button.Background = (Brush)FindResource("ButtonNormalBackgroundBrush");

答案 1 :(得分:4)

BtnGetBrushes.Background = this.Resources["ButtonNormalBackgroundBrush"] as LinearGradientBrush;