如何在 WPF 后面的代码中复制资源引用? [英] How do I duplicate a resource reference in code behind in WPF?

查看:35
本文介绍了如何在 WPF 后面的代码中复制资源引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有一个颜色资源.我有一个元素将该颜色用作 xaml 中的动态资源.

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;
        }
     }
  }

但是,SetResourceReference 仅适用于 FrameworkElements 或 FrameworkContentElements.SolidColorBrush 只是一个 Freezable.另外,我不知道如何在后面的代码中获取资源引用.

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.

有没有办法在 WPF 中做到这一点,以便两种颜色同时改变?在我的实际应用中,问题并没有那么简单,所以我不能只在 xaml 中添加第二个 DynamicResource.

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.

推荐答案

Il Vic 建议使用反射.对此进行扩展,我能够为 DependencyObject 构建一些可以执行我想要的扩展方法.我真的不喜欢在代码中使用反射,如果其他人知道实现这一点的更好方法,我很乐意看到它.至少,每当我尝试从背后的代码调试 DynamicResources 时,这都会有所帮助.

Il Vic suggested using reflection. Expanding on that, I was able to build some extension methods for DependencyObject that do what I want. I don't really like using reflection in code, and if someone else knows a better way to implement this, I'd love to see it. At least this will be helpful whenever I'm trying to debug DynamicResources from code behind.

  public static class DependencyObjectExtensions
  {
     public static object GetDynamicResourceKey(this DependencyObject obj, DependencyProperty prop)
     {
        // get the value entry from the depencency object for the specified dependency property
        var dependencyObject = typeof(DependencyObject);
        var dependencyObject_LookupEntry = dependencyObject.GetMethod("LookupEntry", BindingFlags.NonPublic | BindingFlags.Instance);
        var entryIndex = dependencyObject_LookupEntry.Invoke(obj, new object[] { prop.GlobalIndex });
        var effectiveValueEntry_GetValueEntry = dependencyObject.GetMethod("GetValueEntry", BindingFlags.NonPublic | BindingFlags.Instance);
        var valueEntry = effectiveValueEntry_GetValueEntry.Invoke(obj, new object[] { entryIndex, prop, null, 0x10 });

        // look inside the value entry to find the ModifiedValue object
        var effectiveValueEntry = valueEntry.GetType();
        var effectiveValueEntry_Value = effectiveValueEntry.GetProperty("Value", BindingFlags.Instance | BindingFlags.NonPublic);
        var effectiveValueEntry_Value_Getter = effectiveValueEntry_Value.GetGetMethod(nonPublic: true);
        var rawEntry = effectiveValueEntry_Value_Getter.Invoke(valueEntry, new object[0]);

        // look inside the ModifiedValue object to find the ResourceReference
        var modifiedValue = rawEntry.GetType();
        var modifiedValue_BaseValue = modifiedValue.GetProperty("BaseValue", BindingFlags.Instance | BindingFlags.NonPublic);
        var modifiedValue_BaseValue_Getter = modifiedValue_BaseValue.GetGetMethod(nonPublic: true);
        var resourceReferenceValue = modifiedValue_BaseValue_Getter.Invoke(rawEntry, new object[0]);

        // check the ResourceReference for the original ResourceKey
        var resourceReference = resourceReferenceValue.GetType();
        var resourceReference_resourceKey = resourceReference.GetField("_resourceKey", BindingFlags.NonPublic | BindingFlags.Instance);
        var resourceKey = resourceReference_resourceKey.GetValue(resourceReferenceValue);

        return resourceKey;
     }

     public static void SetDynamicResourceKey(this DependencyObject obj, DependencyProperty prop, object resourceKey)
     {
        var dynamicResource = new DynamicResourceExtension(resourceKey);
        var resourceReferenceExpression = dynamicResource.ProvideValue(null);
        obj.SetValue(prop, resourceReferenceExpression);
     }
  }

第二种方法使用 DynamicResourceExtension 来避免 Activator 的一些麻烦,但第一种方法感觉非常脆弱.

The second method uses DynamicResourceExtension to avoid some nastiness with Activator, but the first method feels incredibly brittle.

我可以在原始示例中使用这些方法,如下所示:

I can use these methods in my original example as follows:

  public MainWindow() {
     InitializeComponent();

     var key = TopBrush.GetDynamicResourceKey(SolidColorBrush.ColorProperty);
     BottomBrush.SetDynamicResourceKey(SolidColorBrush.ColorProperty, key);

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

这将适用于任何 DependencyProperty,前提是当我们尝试获取资源键时将其设置为 DynamicResource.生产代码需要更多的技巧.

This will work for any DependencyProperty, provided it is set to a DynamicResource when we try to get the resource key. A little more finesse would be needed for production code.

这篇关于如何在 WPF 后面的代码中复制资源引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆