如何以编程方式设置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看起来与此相似:
<Rectangle x:Name="UI_Boat" Fill="#FFF4F4F5" HorizontalAlignment="Center" Height="100" Stroke="Black" VerticalAlignment="Center" Width="{Binding}"/>
答案 0 :(得分:3)
this.UI_Boat.SetBinding(Rectangle.WidthProperty, new Binding()
{
Path = "Width",
Source = theBoat
});