In my application, I have a color resources. I have one element that uses that color as a dynamic resource in 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>
In the code, I want to duplicate this resource reference.
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;
}
}
}
However, SetResourceReference only works for FrameworkElements or FrameworkContentElements. SolidColorBrush is just a Freezable. Also, I have no idea how to get a resource reference in code behind.
Is there a way to do this in WPF so that both of the colors change at the same time? In my real application, the problem isn't quite so simple, so I can't just add a second DynamicResource in xaml.
SolidColorBrushas a resource itself and then using that for theFillproperties of the elements where you want it. - Peter Duniho