Patrick
Patrick

Reputation: 681

How to bind a property containing a space(-like) character in XAML?

In the DataContext of my TextBox I have an object which exposes a property called "Name Surname".

I have tried these three possibiltie so far:

Text="{Binding selectedEntity.Name Surname}"

Text="{Binding selectedEntity.'Name Surname'}"

Text="{Binding selectedEntity."Name Surname"}"

None does work. Could someone provide me a working example?

EDIT: I create the datacontext object in a powershell runspace like this:

$myObject = New-Object PSObject
$myObject | Add-Member -Name "Sure Name" -Value "test" -MemberType "NoteProperty"

There, I'm allowed to access the property via

$myObject.'Sure Name'.

Upvotes: 0

Views: 1478

Answers (2)

Aman Chaudhary
Aman Chaudhary

Reputation: 200

Try to add binding from codeBehind, may serve the purpose

Binding mB = new Binding();
mB.Source = MyProperty;
myTextBlock.SetBinding(TextBlock.TextProperty, mB);
myTextBlock.DataContext = this;

Upvotes: 0

helb
helb

Reputation: 7793

Using the space character (Unicode code point value 32) in an identifier name is not allowed.

The property name was either generated with some other unicode character which looks like a space or the class was generated in IL where identifiers can contain characters which are invalid in C#.

You should try to figure out why the property has that name and try to fix the naming first. If you don't know which characters are used in the generated class you are lost anyway.

XAML allows escaping special characters though. If your property name contains for example a space character (0x20) you can try with:

Text="{Binding selectedEntity.Name Surname}"

More about Spaces in identifier names which may be interesting (or nightmare-inducing...)

Upvotes: 4

Related Questions