【发布时间】:2014-09-26 13:22:35
【问题描述】:
如何以编程方式设置 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}"/>
【问题讨论】:
-
我知道这不是你问的,但是
<Rectangle Width="{Binding Path=Width}" />有什么问题? -
@TzahMama 将其添加到 Xaml 并更改 Height="100" 显示了正确的行为;需要解释一下吗?
-
好吧
Binding Path="Something"转到您的DataContext并搜索Something属性。如果找到一个(并且对于所需的类型是可接受的),它将被用作值。你甚至可以去Path=Something.SomeNumber的属性
标签: c# xaml data-binding datacontext