如何从XAML中定义的ResourceDictionary中检索Brush并在代码中应用于元素?

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

    <LinearGradientBrush x:Key="ButtonNormalBackgroundBrush"
        StartPoint = "0.5,0"
        EndPoint   = "0.5,1">

        <GradientStop Color="#C10099FF" Offset="0"/>
        <GradientStop Color="#C16699CC" Offset="1"/>
        <GradientStop Color="#C1006699" Offset="0.49"/>

    </LinearGradientBrush>

<ResourceDictionary/>

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

 BtnGetBrushes.Background = Brushes.Green;

我想使用上面的颜色代替这个(Brushes.Green)。我该怎么做?
2个回答

19

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

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

或者在代码中

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

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

在我的Windows Phone 8.0 Silverlight上可以运行。 - aloisdg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接