简体   繁体   English

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

[英]How can you retrieve a Brush from a ResourceDictionary defined in XAML and apply it to an element in code?

<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/>

Now i want to get LinearGradientBrush from ResourceDictonary and apply it dynamically to a button as background color in wpf.现在我想从 ResourceDictonary 获取 LinearGradientBrush 并将其动态应用到按钮作为 wpf 中的背景颜色。

 BtnGetBrushes.Background = Brushes.Green;

I want to apply the above color instead of this(Brushes.Green).我想应用上面的颜色而不是这个(Brushes.Green)。 what should i do for that ?我该怎么做?

Assuming your ResourceDictionary available in the context:假设您的 ResourceDictionary 在上下文中可用:

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

or in Code或在代码中

button.Background = (Brush)FindResource("ButtonNormalBackgroundBrush");
BtnGetBrushes.Background = this.Resources["ButtonNormalBackgroundBrush"] as LinearGradientBrush;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在XAML中使用定义的画笔资源,来自C# - How to use a defined brush resource in XAML, from C# 在XAML中应用自定义画笔 - Apply custom brush in XAML 如何在运行时将多次在XAML ResourceDictionary中定义的Path添加到WPF表单? - How can I add a Path, that has been defined in the XAML ResourceDictionary, multiple times to a WPF form at runtime? 如何从XAML中定义的数据模板以编程方式创建元素? - How do you create an element programmatically from a data template defined in XAML? 如何从 C# 代码访问 wpf 中的 ResourceDictionary? - How can I access ResourceDictionary in wpf from C# code? C# - 如何从xaml resourcedictionary格式的字符串中获取密钥和值? - C# - How can I get the key and value from strings of xaml resourcedictionary format? WinRT XAML尝试使用ResourceDictionary中定义的路径,但是“元素已经是另一个元素的子元素。” - WinRT XAML trying to use a Path defined in ResourceDictionary, but “Element is already the child of another element.” 如何在自身上应用定义的属性? - how you can apply an defined attribute on itself? WPF:如何访问后面的ResourceDictionary代码中的元素 - WPF: How to access element in ResourceDictionary code behind 如何在另一个XAML文件中访问ResourceDictionary属性后面的代码? - How to access a code behind property of ResourceDictionary in another XAML file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM