OneWay wiążące
Załóżmy, że masz klasę Country
z własności statyczne Name
.
public class Country
{
public static string Name { get; set; }
}
a teraz chcesz właściwość wiązania do TextProperty
Name
z TextBlock
.
Binding binding = new Binding();
binding.Source = Country.Name;
this.tbCountry.SetBinding(TextBlock.TextProperty, binding);
Aktualizacja: TwoWay wiążące
Country
klasy wygląda następująco:
public static class Country
{
private static string _name;
public static string Name
{
get { return _name; }
set
{
_name = value;
Console.WriteLine(value); /* test */
}
}
}
A teraz chcemy wiążący tę właściwość Name
do TextBox
, więc:
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);
Jeśli chcesz zaktualizować celu należy użyć BindingExpression
i funkcji UpdateTarget
:
Country.Name = "Poland";
BindingExpression be = BindingOperations.GetBindingExpression(this.tbCountry, TextBox.TextProperty);
be.UpdateTarget();