2008年7月3日星期四

Data Binding

Data Binding is a key concept in WPF.

Why I can NOT data bind my class ?

public class MyClass
{
public string MyPorperty { get; set; }
}
First time, I trid to bind MyProperty in MyClass to a TextBox, but I can NOT. Why? Because I did not derived my class from interface INotifyPropertyChanged.

public class MyClass : INotifyPropertyChanged
{...}


Yes, we have to implement the interface. Csharp is a great programming language, but not magician words. So when your data changed, you have to tell the framework the change happened. That's why you need the interface.

Same reason, when you implement you own collection class, you have implement the INotifyCollectionChanged. You may encounter some problem when you want to bind a List to ComboBox/ListBox/ListView. No, you are using the wrong class, you should use ObservableCollection instead.

Use ValidationRule to check your input






-

Let's use TextBox as a sample. You can set a validation rule to the binding. When the rule check failed, a red ring will around the text box.

Related classes: System.Windows.Data.Binding, System.Windows.Controls.ValidationRule

-------------------------------------------

Some Other Good Readings:

  1. Binding menus using HeirarchicalDataTemplates

没有评论: