How do I duplicate a resource reference in code behind in WPF?如何在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后台代码中中复制引用的资源?的更多相关文章
- error: <item> inner element must either be a resource reference or empty.
FAQ: Android resource compilation failedOutput: /home/cmm/code/AndroidHttpCapture/app/build/intermed ...
- 解决问题 inner element must either be a resource reference or empty.
-Q: 错误<item>内部元素必须是资源引用或空 升级Andriod Studio之后编译发现如下错误 Android resource compilation failed ***\a ...
- 理解Java中的弱引用(Weak Reference)
本篇文章尝试从What.Why.How这三个角度来探索Java中的弱引用,理解Java中弱引用的定义.基本使用场景和使用方法.由于个人水平有限,叙述中难免存在不准确或是不清晰的地方,希望大家可以指出, ...
- Illegal resource reference: @*android resources are private and not always present
0:前言 在android开发中,当使用别人的代码的时候,在style.xml中有此种错误 1:解决方案 删除*星号
- windows phone 7 中怎样定义和使用资源(Resource)
1. 系统资源. 在wp7开发中可以看到很多使用系统资源(resource)的例子,例如默认的新page: http://blog.csdn.net/matrixcl/article/details/ ...
- 【Unity3D】中的空引用 Null Reference Exception
Null Reference Exception : Object reference not set to an instance of an object. 异常:空引用,对象的引用未设置到对象的 ...
- java中的方法引用(method reference)官方文档总结
2017/7/5 转载写明出处:http://www.cnblogs.com/daren-lin/p/java-method-reference.html 今天要说的是java中的一项新特性,方法引用 ...
- 遇到问题---java---myeclipse中maven项目引用另一个导致的resource文件混乱的问题
遇到情况 情况是这样的,我们在构建项目时,经常会把一些公用的类和配置提取出去,作为一个公共项目.然后把公共项目作为一个jar包构件引入我们当前的项目中. 引入方式是 <dependency> ...
- java中的强引用(Strong reference),软引用(SoftReference),弱引用(WeakReference),虚引用(PhantomReference)
之前在看深入理解Java虚拟机一书中第一次接触相关名词,但是并不理解,只知道Object obj = new Object()类似这种操作的时候,obj就是强引用.强引用不会被gc回收直到gc roo ...
随机推荐
- SQLite单表4亿订单,大数据测试
[转载] SQLite单表4亿订单,大数据测试 http://www.cnblogs.com/nnhy/p/BigData.html
- php正则怎么使用(最全最细致)
php正则怎么使用(最全最细致) 一.总结 一句话总结: 1.正则中的行定位符是什么? 解答:(^与$) 2.正则中什么时候用行定位符? 解答:如"^de",表示以de开头的字符串 ...
- 【矩阵】概念的理解 —— span、基
span:全部列向量的线性组合构成的集合: span[a1,-,an]={y∈Rm|y=∑k=1nckak}=S 注:ak∈Rm,共 n 个列向量: 集合 S 可以有不同的一组基,但是基中向量的个数是 ...
- amazeui中css组件、js组件、web组件的区别
amazeui中css组件.js组件.web组件的区别 一.总结 一句话总结: 1.可直接像调用js插件那样调用:在AmazeUI(妹子UI)中,Web组件可以不编写模板而直接使用,若如此,则与JS插 ...
- erlang tcp发包速度测试
http://blog.sina.com.cn/s/blog_96b8a1540101317m.html 这段时间我们的项目遇到广播包的一些性能问题,想起之前看到yufeng老大提到的1s广播40K包 ...
- App各种Icon及Launch image的尺寸和用途
App各种Icon及Launch image的尺寸和用途 IOS7,8 Asset iPhone 6 Plus (@3x) iPhone 6 and iPhone 5 (@2x) iPhone 4s ...
- Oracle数据库案例整理-Oracle系统执行失败-sql_trace至TRUE导致Oracle在根文件夹中缺乏可用空间
1.1 述 在"$ORACLE_BASE/diag/rdbms/$ORACLE_SID/$ORACLE_SID/trace"文件夹下产生大量"oracle_w ...
- Java 联系Oracle 数据库
一般完成 import oracle.jdbc.driver.*; 会后声明,你会发现一个错误.然后,你需要: 一.该JDBC开车到classpath 两种方法.一是图形化,计算机-属性-高级设置-环 ...
- WPF--3Dmax+blend+WPF综合运用
引自:http://blog.sina.com.cn/s/blog_95dbdf9e0100we3z.html 本人小菜,WPF刚入门,只是写一下最近的项目心得.欢迎各位前辈们前来拍砖指正,感激不敬! ...
- 一句话的设计模式(JAVA版)
·结构型模式: o适配器:用来把一个接口转化成另一个接口,如 java.util.Arrays#asList(). o桥接模式:这个模式将抽象和抽象操作的实现进行了解耦,这样使得抽象和实现可以独立地变 ...