Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF parse binding expression

Tags:

c#

.net

binding

wpf

Is there any way of turning a string containing a binding expression into a Binding object?

A simple example would be "{Binding Path}",

or:

"{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=views:IPage}, Path=TensileTestChange}"

The actual binding expression is stored in XML, which is a higher-level representation of a XAML document.

like image 580
Darkzaelus Avatar asked Feb 04 '26 18:02

Darkzaelus


1 Answers

What you are asking is to parse a MarkupExtension. I could not find WPF's implementation directly (it's contained somewhere in the XamlReader.Parse call chain).

After some googling, it seems there is no ready made solution available to do this. However, if you have some experience with writing parsers you could roll your own. The specification for parsing a MarkupExtension is given on MSDN.

As a workaround, you could fake a control where you put the binding on:

string myBindingExpression = "{Binding MyProperty}";

var test = "<TextBlock xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" Text=\"" 
    + myBindingExpression + "\" />";
var result = XamlReader.Parse(test) as TextBlock;
var bindingExpression = result.GetBindingExpression(TextBlock.TextProperty);

Binding binding = bindingExpression.ParentBinding

This creates a TextBlock with the binding as the Text property. It will give you the binding object with the properties set according to the binding expression.

You can then apply the binding wherever.

Remember though, for your more complex example with the xmlns prefix, you need to include the xmlns:views="..." in the fake TextBlock, otherwise it will not know what to do with the prefix.

Example: <TextBlock xmlns:views="..." xmlns="..." Text="{Binding MyProperty}" />

like image 168
Bas Avatar answered Feb 07 '26 08:02

Bas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!