Impossible WPF Part 2: Binding Expressions
原文 http://www.11011.net/wpf-binding-expressions
Back in April I posted an idea for building an expression converter for use with MultiBindings. This is a question I often see asked, but the answer is usually "go and write a once off converter" (for an example see the Negate converter in my Transition sample - how useful is that really?). More recently I noticed this sample on LearnWPF which provides single value simple arithmetic conversions. Unfortunately no one ever took the bait and implemented the multi-value converter, so I had to go and do it myself.
The result is the JScriptConverter, which for simplicity of use is both an IMultiValueConverter and an IValueConverter. There are numerous benefits to using JScript here:
- It's part of the framework, so we don't have to go and write our own scanner/parser/interpreter for a new mini language.
- It's a dynamic language, so it nicely complements the dynamically typed binding system of WPF.
- Evaluations in JScript are interpreted not compiled, so we don't leak memory on every evaluation.
The code for the conveter is once again quite trivial. Because it's quite difficult to set up a JScript environment for evaluation I instead compile a tiny JScript assembly to wrap the evaluations. This is done once statically and then reused by all instances of the class. Note the TrapExceptions property, if this is set to true any exceptions raised during the conversion will result in null.
Using it is easy. Just instantitate the converter as a resource:
<utils:JScriptConverterx:Key="JScript"TrapExceptions="False" />
And wire it up as a single Binding:
<TextBlockText="{Binding ElementName=tb1, Path=Text,
Converter={StaticResource JScript},
ConverterParameter=Int32.Parse(values[0])/100.0"/>
Or as a MultiBinding:
<MultiBindingConverter="{StaticResource JScript}"ConverterParameter=
"new System.Windows.Thickness(values[0]*0.1/2,values[1]*0.1/2,0,0)">
<BindingRelativeSource="{RelativeSource TemplatedParent}"Path="ActualWidth" />
<BindingRelativeSource="{RelativeSource TemplatedParent}"Path="ActualHeight" />
</MultiBinding>
I'm not so happy with the code that enumerates and adds references to all the Assemblies in the current AppDomain, but for the time being it serves its purpose.
Anyway, without further ado (of course this requires a reference to Microsoft.JScript). Cut and paste as you please:
using System;
using System.Windows.Data;
using System.CodeDom.Compiler;
using System.Reflection; namespace Utils.Avalon
{
public sealed class JScriptConverter : IMultiValueConverter, IValueConverter
{
private delegate object Evaluator(string code, object[] values);
private static Evaluator evaluator; static JScriptConverter()
{
string source =
@"import System; class Eval
{
public function Evaluate(code : String, values : Object[]) : Object
{
return eval(code);
}
}"; CompilerParameters cp = new CompilerParameters();
cp.GenerateInMemory = true;
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
if (System.IO.File.Exists(assembly.Location))
cp.ReferencedAssemblies.Add(assembly.Location); CompilerResults results = (new Microsoft.JScript.JScriptCodeProvider())
.CompileAssemblyFromSource(cp, source); Assembly result = results.CompiledAssembly; Type eval = result.GetType("Eval"); evaluator = (Delegate.CreateDelegate(
typeof(Evaluator),
Activator.CreateInstance(eval),
"Evaluate") as Evaluator);
} private bool trap = false;
public bool TrapExceptions
{
get { return this.trap; }
set { this.trap = true; }
} public object Convert(object[] values, System.Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
try
{
return evaluator(parameter.ToString(), values);
}
catch
{
if (trap)
return null;
else
throw;
}
} public object Convert(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
return Convert(new object[] { value }, targetType, parameter, culture);
} public object[] ConvertBack(object value, System.Type[] targetTypes,
object parameter, System.Globalization.CultureInfo culture)
{
throw new System.NotSupportedException();
} public object ConvertBack(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
throw new System.NotSupportedException();
}
}
}
Impossible WPF Part 2: Binding Expressions的更多相关文章
- Impossible WPF Part 1: Binding Properties
原文 http://www.11011.net/wpf-binding-properties Ever wanted to write the following? <RichTextBoxDo ...
- 【转】WPF中的Binding技巧(二)
WPF中的Binding技巧(二) 接上篇, 我们来看一看Elementname,Source,RelativeSource 三种绑定的方式 1.ElementName顾名思义就是根据Ui元素 ...
- [XAML]类似WPF绑定的Binding的读取方法
在WPF的XAML里,依赖属性可以使用基于BindingBase之类的MarkupExtensin 读取XAML时,会自动的把该BindingBase转换为BindingExpressionBase ...
- [WPF系列]-使用Binding来同步不同控件的Dependency property
简介 项目中经常会用到,同步两个控件的值,本文就简单列举两种方式来同步不同控件的两个Dependency Property. 示例 效果图: 只使用C#代码: //获取slider1的ValueDep ...
- (WPF) 再议binding:点击User Control时,User Control变换颜色或做其他的处理。
Binding 是前台UI(显示层)和后台代码(数据层)的桥梁.理论上当后台的数据变动时,显示的数据或样式应该随之而变.这些是动态的. 对于Binding的设置可以在前台Xaml,也可以在后台Code ...
- 解读WPF中的Binding
1.Overview 基于MVVM实现一段绑定大伙都不陌生,Binding是wpf整个体系中最核心的对象之一这里就来解读一下我花了纯两周时间有哪些秘密.这里我先提出几个问题应该是大家感兴趣的,如下: ...
- (WPF, MVVM) Textbox Binding
参考:http://msdn.microsoft.com/en-us/library/system.windows.data.updatesourcetrigger(v=vs.110).aspx Te ...
- (WPF, MVVM) Slider Binding.
对于Button的Command的绑定可以通过实现ICommand接口来进行,但是Slider并没有Command属性. 另外如果要实现MVVM模式的话,需要将一些Method和Slider的Even ...
- (WPF) MVVM: DataGrid Binding
Binding到DataGrid的时候,需要用到ObservableCollection. public ObservableCollection<Customer> Customers ...
随机推荐
- 电感耦合非接触IC卡系统的EMI问题
射频识别(RFID)技术近年来发展迅速,并获得了广泛应用.但作为一种无线射频技术,其电磁兼容(EMC)性能也越来越受到人们的关注.RFID涉及的频率范围甚广,包括低于135kHz.13.56MHz.4 ...
- PowerPoint2003/2007幻灯片常用快捷键大全
熟习掌握PowerPoint快捷键不仅可以对我们在制作幻灯片的时候更加熟练节省时间.而且在我们演示PPT文稿的时候,也不需要停下演讲去调试菜单工具来切换下一张,我们只需要轻轻的按一下键盘即可轻松切换P ...
- 无法启动此程序,因为计算机中丢失QtCore4.dll。尝试重新安装该程序以解决此问题(在系统里添加3个路径)
解决方法: 计算机-属性-高级系统设置-高级-环境变量-系统变量-Path 添加 E:\Qt\4.8.5\bin; E:\Qt\4.8.5\qmake; E:\mingw\bin 重启计算机 http ...
- Android JNI开发提高篇
有关JNI的开发技术,我们继续围绕Android平台进行,JNI可以支持C或C++,从目前为止我们写过的JNI代码均为C实现的,即文件名为.C而C++的和这些有什么不同呢? Android平台上的JN ...
- 远程登录 Windows server 2008 黑屏
scenerio: 远程登录 Windows server 2008 黑屏,别人那里一切正常. Solution:在黑屏界面,点击桌面,按住Ctrl+Alt+End键 -> Log Off. ...
- 语句分类及if语句
一.语句分类: 1.顺序语句2.分支语句 if语句.switch语句 3.循环语句 (1)初始条件 (2)循环条件 (3)循环体 (4)状态改变 二.if语句: 1.if语句4中情况: if(条件){ ...
- BZOJ 1692: [Usaco2007 Dec]队列变换( 贪心 )
数据 n <= 30000 , 然后 O( n² ) 的贪心也过了..... USACO 数据是有多弱啊 = = ( ps : BZOJ 1640 和此题一模一样 , 双倍经验 ) ------ ...
- BZOJ 1711: [Usaco2007 Open]Dingin吃饭( 最大流 )
将牛拆成两个点 i 和 i' 并连弧 , S 向每种 food 连边 , 每种 drink 向 T 连边 , 每种 food 向喜欢他的 cow 连边 到 i , 每种 drink 从喜欢它的 cow ...
- BZOJ 1627: [Usaco2007 Dec]穿越泥地( BFS )
BFS... --------------------------------------------------------------------------------------- #incl ...
- HLS 协议
HTML 5 视频直播一站式扫盲 本文来自于腾讯bugly开发者社区,原文地址:http://bugly.qq.com/bbs/forum.php?mod=viewthread&tid=1 ...