1

私のアプリケーションには、カラー リソースがあります。その色を 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 を追加することはできません。

4

2 に答える 2

2

実際、 という内部オブジェクトが必要ですResourceReferenceExpression。DynamicResourceExtention で使用されます。

これはあなたが使用できるコードです:

public MainWindow()
{
    InitializeComponent();

    BottomBrush.SetValue(SolidColorBrush.ColorProperty,
        Activator.CreateInstance(Type.GetType("System.Windows.ResourceReferenceExpression, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"), "MyColor"));

    Resources["MyColor"] = Colors.Green;
}

慎重に使用してください!は内部的なものなのでResourceReferenceExpression、おそらく理由があるでしょう (そのオブジェクトを間違って使用すると、メモリ リークが発生する可能性があります)。

于 2015-01-30T17:20:21.243 に答える