【发布时间】:2015-02-03 00:57:29
【问题描述】:
在我的应用程序中,我有一个颜色资源。我有一个元素使用该颜色作为 xaml 中的动态资源。
<Window x:Class="ResourcePlay.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="425">
<Window.Resources>
<Color x:Key="MyColor">Red</Color>
</Window.Resources>
<Grid>
<Rectangle VerticalAlignment="Top" Width="80" Height="80" Margin="10">
<Rectangle.Fill>
<SolidColorBrush x:Name="TopBrush" Color="{DynamicResource MyColor}"/>
</Rectangle.Fill>
</Rectangle>
<Rectangle VerticalAlignment="Bottom" Width="80" Height="80" Margin="10">
<Rectangle.Fill>
<SolidColorBrush x:Name="BottomBrush"/>
</Rectangle.Fill>
</Rectangle>
</Grid>
</Window>
在代码中,我想复制这个资源引用。
using System.Windows;
using System.Windows.Media;
namespace ResourcePlay {
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
// I want to copy the resource reference, not the color.
BottomBrush.Color = TopBrush.Color;
// I'd really rather do something like this.
var reference = TopBrush.GetResourceReference(SolidColorBrush.ColorProperty);
BottomBrush.SetResourceReference(reference);
// I want this to change the colors of both elements
Resources["MyColor"] = Colors.Green;
}
}
}
但是,SetResourceReference 仅适用于 FrameworkElements 或 FrameworkContentElements。 SolidColorBrush 只是一个 Freezable。另外,我不知道如何在后面的代码中获取资源引用。
有没有办法在 WPF 中做到这一点,以便两种颜色同时改变?在我的实际应用程序中,问题并不是那么简单,所以我不能只在 xaml 中添加第二个 DynamicResource。
【问题讨论】:
-
请详细解释为什么您不简单地将
SolidColorBrush声明为资源本身,然后将其用于所需元素的Fill属性。 -
@PeterDuniho 这里的 SolidColorBrush 是我在应用程序中使用的自定义 Freezable 子类的代理。真正的对象是为依赖注入参数化的,所以我不能在 xaml 中创建对象。
-
不知道为什么有人会否决一个问题,因为这也是我的确切问题。这个帖子为我提供了一个解决方案。
标签: c# wpf xaml dynamicresource