OneWay ràng buộc
Giả sử rằng bạn có lớp Country
với tài sản Name
tĩnh.
public class Country
{
public static string Name { get; set; }
}
Và bây giờ bạn muốn ràng buộc tài sản Name
-TextProperty
của TextBlock
.
Binding binding = new Binding();
binding.Source = Country.Name;
this.tbCountry.SetBinding(TextBlock.TextProperty, binding);
Cập nhật: TwoWay ràng buộc
Country
lớp trông như thế này:
public static class Country
{
private static string _name;
public static string Name
{
get { return _name; }
set
{
_name = value;
Console.WriteLine(value); /* test */
}
}
}
Và bây giờ chúng tôi muốn ràng buộc tài sản Name
này để TextBox
, vì vậy:
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);
Nếu bạn muốn cập nhật mục tiêu mà bạn phải sử dụng BindingExpression
và chức năng UpdateTarget
:
Country.Name = "Poland";
BindingExpression be = BindingOperations.GetBindingExpression(this.tbCountry, TextBox.TextProperty);
be.UpdateTarget();