namespace BindingWPF
{
public partial class MainWindow : Window
{
private Person Person;
public MainWindow()
{
InitializeComponent();
Person = new Person("zhang", 18, new DateTime(2008, 5, 1));
UIdataBinding();
}
private void UIdataBinding()
{
BindText(this.textBox1,Person, "Name"); // 绑定Name成功
Person.Name = "Li";
//this.textBox2 绑定Age
//this.textBox2 绑定 BirthDay
//需要双向绑定
}
static void BindText(TextBox textBox,object obj ,string property)
{
DependencyProperty textProp = TextBox.TextProperty;
if (!BindingOperations.IsDataBound(textBox, textProp))
{
textBox.DataContext = obj;
Binding b = new Binding(property);
b.Mode = BindingMode.TwoWay;
b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(textBox, textProp, b);
}
}
}
public class Person :INotifyPropertyChanged
{
private string name;
private UInt16 age;
private DateTime birthDay;
public event PropertyChangedEventHandler PropertyChanged;
public string Name
{
get{return this.name;}
set{
this.name=value;
OnPropertyChanged("Name");
}
}
public UInt16 Age
{
get { return this.age; }
set
{
this.age = value;
OnPropertyChanged("Age");
}
}
public DateTime BirthDay
{
get { return this.birthDay; }
set
{
this.birthDay = value;
OnPropertyChanged("BirthDay");
}
}
public Person(string Name, UInt16 Age, DateTime BirthDay)
{
this.Name = Name;
this.Age = Age;
this.BirthDay = BirthDay;
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
/// <summary>DateTime类和String类的数据转换</summary>
[ValueConversion(typeof(DateTime), typeof(String))]
public class DateConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
DateTime date = (DateTime)value;
return date.ToShortDateString();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
string strValue = value as string;
DateTime resultDateTime;
if (DateTime.TryParse(strValue, out resultDateTime))
{
return resultDateTime;
}
return DependencyProperty.UnsetValue;
}
}
}