How to bind to static property programmatically? What can I use in C# to make
{Binding Source={x:Static local:MyClass.StaticProperty}}
Update: is it possible to do OneWayToSource binding? I understand that TwoWay is not possible because there are no update events on static objects (at least in .NET 4). I cannot instantiate object because it is static.
OneWay binding
Let's assume that you have class Country
with static property Name
.
public class Country
{
public static string Name { get; set; }
}
And now you want binding property Name
to TextProperty
of TextBlock
.
Binding binding = new Binding();
binding.Source = Country.Name;
this.tbCountry.SetBinding(TextBlock.TextProperty, binding);
Update: TwoWay binding
Country
class looks like this:
public static class Country
{
private static string _name;
public static string Name
{
get { return _name; }
set
{
_name = value;
Console.WriteLine(value); /* test */
}
}
}
And now we want binding this property Name
to TextBox
, so:
Binding binding = new Binding();
binding.Source = typeof(Country);
binding.Path = new PropertyPath(typeof(Country).GetProperty("Name"));
binding.Mode = BindingMode.TwoWay;
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
this.tbCountry.SetBinding(TextBox.TextProperty, binding);
If you want update target you must use BindingExpression
and function UpdateTarget
:
Country.Name = "Poland";
BindingExpression be = BindingOperations.GetBindingExpression(this.tbCountry, TextBox.TextProperty);
be.UpdateTarget();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With