如何使用C#xaml以编程方式设置数据绑定 [英] How to programmatically set data binding using C# xaml
本文介绍了如何使用C#xaml以编程方式设置数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何以编程方式设置DataContext并在C#Xaml中创建数据绑定?
How do you programmatically set the DataContext and create a data binding in 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 Rectangle的宽度。
I am trying to programmatically set the Width of a Xaml Rectangle using data binding.
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看起来与此类似:
Where the Xaml look similar to this:
<Rectangle x:Name="UI_Boat" Fill="#FFF4F4F5" HorizontalAlignment="Center" Height="100" Stroke="Black" VerticalAlignment="Center" Width="{Binding}"/>
推荐答案
this.UI_Boat.SetBinding(Rectangle.WidthProperty, new Binding()
{
Path = "Width",
Source = theBoat
});
这篇关于如何使用C#xaml以编程方式设置数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文