如何使用c# xaml编程设置数据绑定

本文关键字:设置 数据绑定 编程 xaml 何使用 | 更新日期: 2023-09-27 18:16:09

如何以编程方式设置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}"/>

如何使用c# xaml编程设置数据绑定

 this.UI_Boat.SetBinding(Rectangle.WidthProperty, new Binding()
            {
                Path = "Width",
                Source = theBoat
            });