Welcome to WindowsClient.net | Sign in | Join

Cristian Ricciolo Civera

Windows Presentation Foundation, C++ CLI, LINQ and experiments

Sponsors





  • advertise here

Lambda Expression into XAML markup

When I write markup I often need an IValueConverter for a Binding and usually the code implementation is small and easy. So, to resolve this typical need I thought that should be useful include small c# expression into the markup.

So I developed a MarkupExtension, called ExpressionExtension that evaluate expression during markup analyzes in order to return value to the target property. To parse the expression I used the DynamicLinq sample of SDK 3.5 which contains an useful DynamicExpression.ParseLambda method to obtain a LambdaExpression from a string. Moreover, evaluating the target property, if this is a IValueConverter, I automatically create a class, implementing the interface, that takes the delegate to convert value for a Binding. This code is compiled so is as fast as a normal c# code.

This is a partial code to understand the functionality:

// Normal expression to evaluate immediately
LambdaExpression le = DynamicExpression.ParseLambda<ExpressionDelegate>(
 
new ParameterExpression[] { 
   
Expression.Parameter(typeof(object), "target")
 
},
 
typeof(object),
 
this.ConvertExpression,
 
null);

ExpressionDelegate converter = (ExpressionDelegate)le.Compile();
return converter(provideValueTarget.TargetProperty);

Here how you can use this new MarkupExtension:

<TextBox x:Name="txt" Text="Testo" />

<
TextBlock
  Text="{Binding Path=Text,ElementName=txt,
  Converter={m:Expression value.ToString().ToUpper(culture)}}"
 />

<
TextBlock Text="{m:Expression DateTime.Now.ToShortDateString()}" />
 
Here you can find the sample and source code.
 
In XAML 2009 there's a special syntax that will allows to use expression: Text="[DateTime.Now.ToShortDateString()]"
Posted: Nov 11 2008, 05:35 PM by RiccioloCristian | with no comments
Filed under:

Comments

No Comments

Leave a Comment

(required) 

(required) 

(optional)

(required) 

Page view counter