Binding Setter.Value from code
Asked Answered
I

1

8

In XAML I can write something like this:

<Setter Property="PropertyName" Value="{Binding ...}" />

How would I do this in code? I've constructed bindings in code before, but I can't seem to find any static ValueProperty object on the Setter class to pass to BindingOperations.SetBinding().

Inertia answered 13/6, 2010 at 0:59 Comment(0)
T
13

When setting a binding on a Setter you don't need BindingOperations at all. All you need to do is:

var setter = new Setter(TextBlock.TextProperty, new Binding("FirstName"));

or equivalently

var setter = new Setter
{
  Property = TextBlock.TextProperty,
  Value = new Binding("FirstName"),
};

either of these would be equivalent to

<Setter Property="TextBlock.Text" Value="{Binding FirstName}" />

The reason this works is that Setter.Value is an ordinary CLR property, not a DependencyProperty and as such it can't be bound. So there is no ambiguity in either the XAML or the code when you store a Binding object in it.

When the Setter is actually applied to an object, if a Binding is found in the Setter, the equivalent of BindingOperations.SetBinding is called. Otherwise the property is set directly.

Tumbrel answered 13/6, 2010 at 3:39 Comment(1)
Ah, thanks for clearing that up. It seemed odd to me that there was no ValueProperty in Setter, but I never thought of just setting the value to a Binding object. :) Cheers Ray--you've been helping me a lot lately. ;)Inertia

© 2022 - 2024 — McMap. All rights reserved.