Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind to static property programmatically?

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.

like image 286
Poma Avatar asked Nov 25 '12 09:11

Poma


1 Answers

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();
like image 123
kmatyaszek Avatar answered Sep 21 '22 23:09

kmatyaszek