wpf 如何从 XAML 中定义的 ResourceDictionary 检索 Brush 并将其应用于代码中的元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12152803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can you retrieve a Brush from a ResourceDictionary defined in XAML and apply it to an element in code?
提问by Chandru A
<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). what should i do for that ?
我想应用上面的颜色而不是这个(Brushes.Green)。我该怎么做?
回答by Jf Beaulac
Assuming your ResourceDictionary available in the context:
假设您的 ResourceDictionary 在上下文中可用:
<Button Background="{DynamicResource ResourceKey=ButtonNormalBackgroundBrush}" />
or in Code
或在代码中
button.Background = (Brush)FindResource("ButtonNormalBackgroundBrush");
回答by Hassan Boutougha
BtnGetBrushes.Background = this.Resources["ButtonNormalBackgroundBrush"] as LinearGradientBrush;

