原文 https://stackoverflow.com/questions/28240528/how-do-i-duplicate-a-resource-reference-in-code-behind-in-wpf

如何在WPF后台代码中中复制引用的资源?

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="" Width="">
<Window.Resources>
<Color x:Key="MyColor">Red</Color>
</Window.Resources>
<Grid>
<Rectangle VerticalAlignment="Top" Width="" Height="" Margin="">
<Rectangle.Fill>
<SolidColorBrush x:Name="TopBrush" Color="{DynamicResource MyColor}"/>
</Rectangle.Fill>
</Rectangle>
<Rectangle VerticalAlignment="Bottom" Width="" Height="" Margin="">
<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.
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[]); // 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[]); // 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);
}
} 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;
} 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.

How do I duplicate a resource reference in code behind in WPF?如何在WPF后台代码中中复制引用的资源?的更多相关文章

  1. error: <item> inner element must either be a resource reference or empty.

    FAQ: Android resource compilation failedOutput: /home/cmm/code/AndroidHttpCapture/app/build/intermed ...

  2. 解决问题 inner element must either be a resource reference or empty.

    -Q: 错误<item>内部元素必须是资源引用或空 升级Andriod Studio之后编译发现如下错误 Android resource compilation failed ***\a ...

  3. 理解Java中的弱引用(Weak Reference)

    本篇文章尝试从What.Why.How这三个角度来探索Java中的弱引用,理解Java中弱引用的定义.基本使用场景和使用方法.由于个人水平有限,叙述中难免存在不准确或是不清晰的地方,希望大家可以指出, ...

  4. Illegal resource reference: @*android resources are private and not always present

    0:前言 在android开发中,当使用别人的代码的时候,在style.xml中有此种错误 1:解决方案 删除*星号

  5. windows phone 7 中怎样定义和使用资源(Resource)

    1. 系统资源. 在wp7开发中可以看到很多使用系统资源(resource)的例子,例如默认的新page: http://blog.csdn.net/matrixcl/article/details/ ...

  6. 【Unity3D】中的空引用 Null Reference Exception

    Null Reference Exception : Object reference not set to an instance of an object. 异常:空引用,对象的引用未设置到对象的 ...

  7. java中的方法引用(method reference)官方文档总结

    2017/7/5 转载写明出处:http://www.cnblogs.com/daren-lin/p/java-method-reference.html 今天要说的是java中的一项新特性,方法引用 ...

  8. 遇到问题---java---myeclipse中maven项目引用另一个导致的resource文件混乱的问题

    遇到情况 情况是这样的,我们在构建项目时,经常会把一些公用的类和配置提取出去,作为一个公共项目.然后把公共项目作为一个jar包构件引入我们当前的项目中. 引入方式是 <dependency> ...

  9. java中的强引用(Strong reference),软引用(SoftReference),弱引用(WeakReference),虚引用(PhantomReference)

    之前在看深入理解Java虚拟机一书中第一次接触相关名词,但是并不理解,只知道Object obj = new Object()类似这种操作的时候,obj就是强引用.强引用不会被gc回收直到gc roo ...

随机推荐

  1. ios开发处理服务器返回的时间字符串

    #import <Foundation/Foundation.h> void other(); void string2date(); int main(int argc, const c ...

  2. vimrum

    # Insert your preferred key mappings here.unmap <a-O>map <a-O> closeOtherTabsmap , previ ...

  3. .NET-架构优化实战-梳理篇

    原文:.NET-架构优化实战-梳理篇 前言 程序员输出是他敲写的代码,那么输入就是他思考好的设计.因此不做设计是不存在,设计只分优秀的设计和糟糕的设计.为了避免过度设计浪费成本,需要针对现有业务与问题 ...

  4. ArcGIS Engine中正确释放打开资源

    转自原文 ArcGIS Engine中正确释放打开资源 AE中对MDB,SDE等数据库操作时,打开后却往往不能及时释放资源,导致别人操作提示对象被锁定. 很多帖子说了很多原理,看的也烦且不实用,比如一 ...

  5. pthread_join/pthread_exit的使用方法解析

    官方说法: 函数pthread_join用来等待一个线程的结束.函数原型为: extern int pthread_join __P ((pthread_t __th, void **__thread ...

  6. Android 判断软键盘弹出并隐藏的简单完美解决方案

    最近项目中有一个编辑框,下面是个ListView.在触发编辑框弹出软键盘后,ListView还能滑动,并且ListView的item还能响应单击.这样的体验效果很不好.于是便想在滑动或单击item时判 ...

  7. 【hdu 3863】No Gambling

    Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65568/32768 K (Java/Others) Total Submission(s) ...

  8. 复杂json解析(json里面嵌套json)

    调用第三方接口,返回一堆json,我只想取得里面的某一个属性,但是返回的比较复杂,无法直接拿到属性,格式类似于这样: {"video":{"id":" ...

  9. Delphi新手跟我学写CALL,附完整原程序

    在开始进入正题前先罗嗦几句: 1.本人也刚学Delphi不久,也刚通过<诛仙>游戏的绝大部分CALL不久.所以在以下所说所列举的例子并不算是名门正中的写法,如有不当,请各位原谅. 2.本人 ...

  10. 【t011】最小覆盖子串

    Time Limit: 1 second Memory Limit: 32 MB [问题描述] 给定一个含有N个元素的序列A,你的任务就是求出序列A的最小覆盖子串的长度. 本题中的一些定义: 串S,是 ...