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

C# 如何使用C xaml以编程方式设置数据绑定,c#,xaml,data-binding,datacontext,C#,Xaml,Data Binding,Datacontext,如何以编程方式设置DataContext并在CXAML中创建数据绑定 上课 class Boat : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; internal void OnPropertyChanged(String info) { PropertyChangedEventHandler handler = PropertyCha

如何以编程方式设置DataContext并在CXAML中创建数据绑定

上课

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}"/>

我知道这不是你问的问题,但有什么问题吗?@TzahMama将其添加到Xaml并更改高度=100显示了正确的行为;需要解释吗?Well Binding Path=某个内容进入您的DataContext并搜索某个属性。如果找到一个符合要求的类型且可接受,则将其用作值。您甚至可以选择properties Path=Something的属性。SomeNumberI知道这不是您所要求的,但有什么问题吗?@TzahMama将其添加到Xaml并更改Height=100显示了正确的行为;需要解释吗?Well Binding Path=某个内容进入您的DataContext并搜索某个属性。如果找到一个符合要求的类型且可接受,则将其用作值。您甚至可以查找properties Path=Something.SomeNumberError的属性:“Windows.UI.Xaml.Data.Binding”不包含带1个参数的构造函数这是在引用,您正在为WP8开发新的BindingWidth吗?你的问题没有找到正确的标签。请参阅我的更新答案。很抱歉缺少标签。我正在开发Windows8应用程序。您的解决方案是正确的,只需添加一项,并做一个小改动。我需要将UI_Boats数据上下文设置为Boat。我需要创建一个新属性path this.UI_Boat.DataContext=this.theBoat;UI_Boat.SetBindingRectangle.WidthProperty,新绑定{Path=new PropertyPathWidth,Source=this.theBoat};错误:“Windows.UI.Xaml.Data.Binding”不包含接受1个参数的构造函数。这是对新BindingWidth的引用,您是为WP8开发的吗?你的问题没有找到正确的标签。请参阅我的更新答案。很抱歉缺少标签。我正在开发Windows8应用程序。您的解决方案是正确的,只需添加一项,并做一个小改动。我需要将UI_Boats数据上下文设置为Boat。我需要创建一个新属性path this.UI_Boat.DataContext=this.theBoat;UI_Boat.SetBindingRectangle.WidthProperty,新绑定{Path=new PropertyPathWidth,Source=this.theBoat};
 this.UI_Boat.SetBinding(Rectangle.WidthProperty, new Binding()
            {
                Path = "Width",
                Source = theBoat
            });