使用 WPF 中的动态资源设置控件背景颜色? [英] Set control Background color using Dynamic Resource in WPF?
问题描述
这是我的 XAML
<Grid.Resources>
<SolidColorBrush x:Key="DynamicBG"/>
</Grid.Resources>
<Label name="MyLabel" Content="Hello" Background="{DynamicResource DynamicBG} />
所以我有两个问题:
问题 1: 我现在如何将代码中的 DynamicBG
键值设置为 Red?(当窗口加载时,我想将其设置为红色)
Q1: How do I go about setting the DynamicBG
key value to Red in my code now? (When the window loads, I'd like to set it to red)
问题 2:动态资源应该这样使用吗?
Q2: Is this how dynamic resources are supposed to be used?
谢谢
推荐答案
要访问代码的 Resource
,必须在文件 App.xaml
中标识它们:
To gain access to the Resource
of the code must identify them in the file App.xaml
:
<Application.Resources>
<SolidColorBrush x:Key="DynamicBG" />
</Application.Resources>
XAML 示例
<Grid>
<Label Name="MyLabel"
Content="Hello"
Background="{DynamicResource DynamicBG}" />
<Button Content="Change color"
Width="100"
Height="30"
Click="Button_Click" />
</Grid>
Resource
可以在以下形式的代码行中更改:
The Resource
can be changed in code line of the form:
Application.Current.Resources["MyResource"] = MyNewValue;
示例:
背后的代码
// using ContentRendered event
private void Window_ContentRendered(object sender, EventArgs e)
{
SolidColorBrush MyBrush = Brushes.Aquamarine;
// Set the value
Application.Current.Resources["DynamicBG"] = MyBrush;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
SolidColorBrush MyBrush = Brushes.CadetBlue;
// Set the value
Application.Current.Resources["DynamicBG"] = MyBrush;
}
原则,DynamicResources
是设计的,所以它们是可以改变的.在哪里更改 - 这是开发人员的任务.对于Color
,它是最常用的方法之一.有关详细信息,请参阅 MSDN.
Principle, DynamicResources
were designed, so they can be changed. Where to change - it is the task of the developer. In the case of Color
, it is one of the most common methods. See the MSDN, for more information.
P.S.我推荐使用App.xaml
,因为曾经有过一个StaticResource
被成功使用的情况,但不是DynamicResource
(资源放在在 Window.Resources
中).但是在 App.xaml
中移动资源后,一切都开始工作了.
P. S. I recommend using App.xaml
, because there have been cases where a StaticResource
has been used successfully, but not DynamicResource
(resources are placed in the Window.Resources
). But after moving the resource in App.xaml
, everything started to work.
这篇关于使用 WPF 中的动态资源设置控件背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!