小编bea*_*ard的帖子

如何使用 C# 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" …
Run Code Online (Sandbox Code Playgroud)

c# data-binding datacontext xaml

3
推荐指数
1
解决办法
1万
查看次数

标签 统计

c# ×1

data-binding ×1

datacontext ×1

xaml ×1