c# - 如何使用 C# xaml 以编程方式设置数据绑定(bind)

标签 c# xaml data-binding datacontext

如何以编程方式设置 DataContext 并在 C# Xaml 中创建数据绑定(bind)?

给定一个类

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");
        }            
    }
}

我正在尝试使用数据绑定(bind)以编程方式设置 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}"/>

最佳答案

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

关于c# - 如何使用 C# xaml 以编程方式设置数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25112421/

相关文章:

c# - AutoFixture.AutoMoq 为一个构造函数参数提供一个已知值

c# - 遍历静态类的属性来填充列表?

c# - 如何使用键连接将值插入 SQL 字段

WPF ComboBox 在是 DependencyObject 时不显示当前项目

c# - 当输入的文本不是数据源的一部分时处理 WPF 可编辑组合框

c# - 数据绑定(bind)和跨线程异常

c# - 无法使用 C# HttpClient 获取任何 cookie

c# - 按索引获取 DataGrid 行

javascript - 使用标签名称插入的组件不起作用

javascript - 通过点击按钮进行多维阵列打印,每行均具有功能