如何使用C#xaml以编程方式设置数据绑定

如何以编程方式设置DataContext并在C#Xaml中创建数据绑定?

鉴于一个类

class Boat : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; internal void OnPropertyChanged(String info) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(info)); } } private int width; public int Width { get { return this.width; } set { this.width = value; OnPropertyChanged("Width"); } } } 

我试图以编程方式使用数据绑定设置Xaml矩形的宽度。

 Boat theBoat = new Boat(); this.UI_Boat.DataContext = this.theBoat; this.UI_Boat.SetBinding(Rectangle.WidthProperty, this.theBoat.Width);//Incorrect this.UI_Boat.SetBinding(Rectangle.WidthProperty, "Width"); //Incorrect 

Xaml看起来与此类似:

  

  this.UI_Boat.SetBinding(Rectangle.WidthProperty, new Binding() { Path = "Width", Source = theBoat });