【问题标题】:How to programmatically set data binding using C# xaml如何使用 C# xaml 以编程方式设置数据绑定
【发布时间】:2014-09-26 13:22:35
【问题描述】:

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

【问题讨论】:

  • 我知道这不是你问的,但是&lt;Rectangle Width="{Binding Path=Width}" /&gt;有什么问题?
  • @TzahMama 将其添加到 Xaml 并更改 Height="100" 显示了正确的行为;需要解释一下吗?
  • 好吧 Binding Path="Something" 转到您的 DataContext 并搜索 Something 属性。如果找到一个(并且对于所需的类型是可接受的),它将被用作值。你甚至可以去Path=Something.SomeNumber的属性

标签: c# xaml data-binding datacontext


【解决方案1】:
 this.UI_Boat.SetBinding(Rectangle.WidthProperty, new Binding()
            {
                Path = "Width",
                Source = theBoat
            });

【讨论】:

  • 错误:'Windows.UI.Xaml.Data.Binding' 不包含采用 1 个参数的构造函数 这是对 new Binding("Width") 的引用
  • 你在为 WP8 开发吗?您在问题中错过了正确的标签。请参阅我的更新答案。
  • 抱歉遗漏了一个标签。我正在开发一个 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 });
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多