在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} />
所以我有两个问题:
第一季度:如何设置 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)
第二季度:应该使用动态资源吗?
Q2: Is this how dynamic resources are supposed to be used?
谢谢
推荐答案
要访问代码的资源
,必须在文件中进行标识。 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>
资源
可以在代码行中更改格式如下:
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屋!