如何在C# Xaml中以编程方式设置DataContext并创建数据绑定?
给定一个类
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}"/>
<Rectangle Width="{Binding Path=Width}" />
有什么问题吗? - Tzah MamaBinding Path="Something"
会去你的DataContext
中查找Something
属性。如果找到了一个(并且它符合所需的类型),它将被用作值。你甚至可以使用属性的属性Path=Something.SomeNumber
。 - Tzah Mama