私のアプリケーションには、カラー リソースがあります。その色を xaml の動的リソースとして使用する要素が 1 つあります。
<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 に 2 つ目の DynamicResource を追加することはできません。