如何从XAML中定义的ResourceDictionary中检索画笔,并将其应用于代码中的元素?

问题描述 投票:9回答:2
<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/>

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

 BtnGetBrushes.Background = Brushes.Green;

我想应用上面的颜色而不是这个颜色(画笔绿色)。我该怎么办?

c# wpf resourcedictionary
2个回答
17
投票

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

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

或使用代码

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

4
投票
BtnGetBrushes.Background = this.Resources["ButtonNormalBackgroundBrush"] as LinearGradientBrush;
© www.soinside.com 2019 - 2024. All rights reserved.