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

bea*_*ard 3 c# data-binding datacontext xaml

如何以编程方式设置 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");
        }            
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用数据绑定以编程方式设置 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
Run Code Online (Sandbox Code Playgroud)

Xaml 看起来与此类似:

<Rectangle x:Name="UI_Boat" Fill="#FFF4F4F5" HorizontalAlignment="Center" Height="100" Stroke="Black" VerticalAlignment="Center" Width="{Binding}"/>
Run Code Online (Sandbox Code Playgroud)

Joh*_*zek 6

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

  • 抱歉缺少标签。我正在开发一个Windows8应用程序。您的解决方案是正确的,只需添加一点并进行一点小小的更改。我需要将 UI_Boats DataContext 设置为 theBoat。我需要创建一个新的 PropertyPath `this.UI_Boat.DataContext = this.theBoat; UI_Boat.SetBinding(Rectangle.WidthProperty, new Binding() { Path = new PropertyPath("Width"), Source = this.theBoat });` (3认同)