How do you create a DynamicResourceBinding that supports Converters, StringFormat?
原文 How do you create a DynamicResourceBinding that supports Converters, StringFormat?
2
down vote
accepted
In the past I've resorted to using several hard-to-follow/hard-to-implement hacks and workarounds to achieve what I feel is missing functionality. That's why to me this is close to (but not quite) the Holy Grail of solutions... being able to use this in XAML exactly like you would a binding, but having the source be a DynamicResource. Note: I say 'Binding' but technically it's a DynamicResourceExtension on which I've defined a Converter, ConverterParameter, ConverterCulture and StringFormat but which does use a Binding internally. As such, I named it based on its usage model, not its actual type. The key to making this work is a unique feature of the Freezable class: If you add a Freezable to the resources of a FrameworkElement, any DependencyProperties on that Freezable which are set to a DynamicResource will resolve those resources relative to that FrameworkElement's position in the Visual Tree. Using that bit of 'magic sauce', the trick is to set a DynamicResource on a Freezable's DependencyProperty, add the Freezable to the resource collection of the target FrameworkElement, then use that Freezable's DependencyProperty as the source for an actual binding. That said, here's the solution. DynamicResourceBinding
public class DynamicResourceBinding : DynamicResourceExtension
{
#region Internal Classes private class DynamicResourceBindingSource : Freezable
{
public static readonly DependencyProperty ResourceReferenceExpressionProperty = DependencyProperty.Register(
nameof(ResourceReferenceExpression),
typeof(object),
typeof(DynamicResourceBindingSource),
new FrameworkPropertyMetadata()); public object ResourceReferenceExpression
{
get { return GetValue(ResourceReferenceExpressionProperty); }
set { SetValue(ResourceReferenceExpressionProperty, value); }
} protected override Freezable CreateInstanceCore()
{
return new DynamicResourceBindingSource();
}
} #endregion Internal Classes public DynamicResourceBinding(){} public DynamicResourceBinding(string resourceKey)
: base(resourceKey){} public IValueConverter Converter { get; set; }
public object ConverterParameter { get; set; }
public CultureInfo ConverterCulture { get; set; }
public string StringFormat { get; set; } public override object ProvideValue(IServiceProvider serviceProvider)
{
// Get the expression representing the DynamicResource
var resourceReferenceExpression = base.ProvideValue(serviceProvider); // If there's no converter, nor StringFormat, just return it (Matches standard DynamicResource behavior}
if(Converter == null && StringFormat == null)
return resourceReferenceExpression; // Create the Freezable-based object and set its ResourceReferenceExpression property directly to the
// result of base.ProvideValue (held in resourceReferenceExpression). Then add it to the target FrameworkElement's
// Resources collection (using itself as its key for uniqueness) so it participates in the resource lookup chain.
var dynamicResourceBindingSource = new DynamicResourceBindingSource(){ ResourceReferenceExpression = resourceReferenceExpression }; // Get the target FrameworkElement so we have access to its Resources collection
// Note: targetFrameworkElement may be null in the case of setters. Still trying to figure out how to handle them.
// For now, they just fall back to looking up at the app level
var targetInfo = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));
var targetFrameworkElement = targetInfo.TargetObject as FrameworkElement;
targetFrameworkElement?.Resources.Add(dynamicResourceBindingSource, dynamicResourceBindingSource); // Now since we have a source object which has a DependencyProperty that's set to the value of the
// DynamicResource we're interested in, we simply use that as the source for a new binding,
// passing in all of the other binding-related properties.
var binding = new Binding()
{
Path = new PropertyPath(DynamicResourceBindingSource.ResourceReferenceExpressionProperty),
Source = dynamicResourceBindingSource,
Converter = Converter,
ConverterParameter = ConverterParameter,
ConverterCulture = ConverterCulture,
StringFormat = StringFormat,
Mode = BindingMode.OneWay
}; // Now we simply return the result of the new binding's ProvideValue
// method (or the binding itself if the target is not a FrameworkElement)
return (targetFrameworkElement != null)
? binding.ProvideValue(serviceProvider)
: binding;
}
}
And just like with a regular binding, here's how you use it (assuming you've defined a 'double' resource with the key 'MyResourceKey')... <TextBlock Text="{drb:DynamicResourceBinding ResourceKey=MyResourceKey, Converter={cv:MultiplyConverter Factor=4}, StringFormat='Four times the resource is {0}'}" />
or even shorter, you can omit 'ResourceKey=' thanks to constructor overloading to match how 'Path' works on a regular binding... <TextBlock Text="{drb:DynamicResourceBinding MyResourceKey, Converter={cv:MultiplyConverter Factor=4}, StringFormat='Four times the resource is {0}'}" />
Awesomesausage! (Well, ok, AwesomeViennasausage thanks to the small 'setter' caveat I uncovered after writing this. I updated the code with the comments.) As I mentioned, the trick to get this to work is using a Freezable. Thanks to its aforementioned 'magic powers' of participating in the Resource Lookup relative to the target, we can use it as the source of the internal binding where we have full use of all of a binding's facilities. Note: You must use a Freezable for this to work. Inserting any other type of DependencyObject into the target FrameworkElement's resources--ironically even including another FrameworkElement--will resolve DynamicResources relative to the Application and not the FrameworkElement where you used the DynamicResourceBinding since they don't participate in localized resource lookup (unless they too are in the Visual Tree of course.) As a result, you lose any resources which may be set within the Visual Tree. The other part of getting that to work is being able to set a DynamicResource on a Freezable from code-behind. Unlike FrameworkElement (which we can't use for the above-mentioned reasons) you can't call SetResourceReference on a Freezable. Actually, I have yet to figure out how to set a DynamicResource on anything but a FrameworkElement. Fortunately, here we don't have to since the value provided from base.ProvideValue() is the result of such a call anyway, which is why we can simply set it directly to the Freezable's DependencyProperty, then just bind to it. So there you have it! Binding to a DynamicResource with full Converter and StringFormat support. For completeness, here's something similar but for StaticResources... StaticResourceBinding
public class StaticResourceBinding : StaticResourceExtension
{
public StaticResourceBinding(){} public StaticResourceBinding(string resourceKey)
: base(resourceKey){} public IValueConverter Converter { get; set; }
public object ConverterParameter { get; set; }
public CultureInfo ConverterCulture { get; set; }
public string StringFormat { get; set; } public override object ProvideValue(IServiceProvider serviceProvider)
{
var staticResourceValue = base.ProvideValue(serviceProvider); if(Converter == null)
return (StringFormat != null)
? string.Format(StringFormat, staticResourceValue)
: staticResourceValue; var targetInfo = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));
var targetFrameworkElement = (FrameworkElement)targetInfo.TargetObject;
var targetDependencyProperty = (DependencyProperty)targetInfo.TargetProperty; var convertedValue = Converter.Convert(staticResourceValue, targetDependencyProperty.PropertyType, ConverterParameter, ConverterCulture); return (StringFormat != null)
? string.Format(StringFormat, convertedValue)
: convertedValue;
}
}
Anyway, that's it! I really hope this helps other devs as it has really simplified our control templates, especially around common border thicknesses and such. Enjoy!
How do you create a DynamicResourceBinding that supports Converters, StringFormat?的更多相关文章
- .NET 框架(转自wiki)
.NET Framework (pronounced dot net) is a software framework developed by Microsoft that runs primari ...
- Revit 2015 API 的全部变化和新功能
这里从SDK的文章中摘录出全部的API变化.主要是希望用户用搜索引擎时能找到相关信息: Major changes and renovations to the Revit API APIchange ...
- Jerry的CDS view自学系列
My CDS view self study tutorial - part 1 how to test odata service generated by CDS view https://blo ...
- kubernetes 实战3_命令_Configure Pods and Containers
Configure a Pod to Use a PersistentVolume for Storage how to configure a Pod to use a PersistentVolu ...
- e666. 创建缓冲图像
A buffered image is a type of image whose pixels can be modified. For example, you can draw on a buf ...
- [英中双语] Pragmatic Software Development Tips 务实的软件开发提示
Pragmatic Software Development Tips务实的软件开发提示 Care About Your Craft Why spend your life developing so ...
- Service官方教程(11)Bound Service示例之2-AIDL 定义跨进程接口并通信
Android Interface Definition Language (AIDL) 1.In this document Defining an AIDL Interface Create th ...
- React搭建项目(全家桶)
安装React脚手架: npm install -g create-react-app 创建项目: create-react-app app app:为该项目名称 或者跳过以上两步直接使用: npx ...
- [译]Vulkan教程(03)开发环境
[译]Vulkan教程(03)开发环境 这是我翻译(https://vulkan-tutorial.com)上的Vulkan教程的第3篇. In this chapter we'll set up y ...
随机推荐
- Android 使用Canvas在图片上绘制文字
一个小应用,在图片上绘制文字,以下是绘制文字的方法,并且能够实现自动换行,字体自动适配屏幕大小 private void drawNewBitmap(ImageView imageView, Stri ...
- Request对象和Response对象详解
Request 1.获取请求的基本信息 1>获取请求的url和uri 2>获取url后面的请求参数部分的字符串 3>获取请求方式 4>获取主机名,IP地址 5>获取 Co ...
- 海思hi3716c机顶盒接usb摄像头和usb无线耳机时,无线耳机有时没有声音
两个USB设备各自是: A:USB摄像头带录音功能,但不带放音功能. B:USB无线耳机是使用USB转2.4G的无线耳机. 详细现象: 1, A,B两者同一时候插上机顶盒,并开机进入android,此 ...
- thinkphp5多级控制器是什么?怎么使用?
thinkphp5多级控制器是什么?怎么使用? 一.总结 1.多级控制器是让控制器的级数变成多级,也就是controller目录下可以新建其它目录. 2.使用的话注意目录下的控制的的命名空间(加上目录 ...
- [TypeScript] Typescript Interfaces vs Aliases Union & Intersection Types
TypeScript has 'interface' and 'type', so when to use which? interface hasName { firstName: string; ...
- L脚本语言实现文件加解密
L脚本语言中能够对内存对象进行AES加解密.我们能够非常easy地实现文件加解密 #scp #定义一个秘钥字符串 定义:字符串,str1,abcdefg 打开:文件,file1,c:\1.txt 打开 ...
- 动态创建Fragment
在android3.0之前.每创建一个界面就要新创建一个activity. 在3.0之后引入了Fragment.相当于一个轻量级的activity.不须要在清单文件配置. 先来看下怎样创建和使用Fra ...
- js进阶 10-4 jquery中基础选择器有哪些
js进阶 10-4 jquery中基础选择器有哪些 一.总结 一句话总结: 1.群组选择器用的符号是什么? 群组选择器,中间是逗号 2.jquery中基础选择器有哪些? 5种,类,id,tag,群组, ...
- 简洁常用权限系统的设计与实现(五):不维护节点的深度level,手动计算level,构造树
这种方式,与第三篇中介绍的类似.不同的是,数据库中不存储节点的深度level,增加和修改时,也不用维护.而是,在程序中,实时去计算的. 至于后面的,按照level升序排序,再迭代所有的节点构造树,与 ...
- 设计模式<面向对象的常用七大设计原则>
面向对象设计的目标之一在于支持可维护性复用,一方面需要实现设计方案或者源码的重用,另一方面要确保系统能够易于扩展和修改,具有较好的灵活性. 常用的设计原则有七个原则: 1.单一职责原则(single ...