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

3

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

给定一个类

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}"/>

我知道这不是你要求的内容,但是 <Rectangle Width="{Binding Path=Width}" /> 有什么问题吗? - Tzah Mama
@TzahMama 将其添加到 Xaml 中并将 Height="100" 更改后,显示了正确的行为;能否解释一下? - beard
1
好的,Binding Path="Something" 会去你的 DataContext 中查找 Something 属性。如果找到了一个(并且它符合所需的类型),它将被用作值。你甚至可以使用属性的属性 Path=Something.SomeNumber - Tzah Mama
1个回答

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

错误: 'Windows.UI.Xaml.Data.Binding' 不包含一个接受1个参数的构造函数。 这是针对新的 Binding("Width") 的引用。 - beard
你在开发WP8吗?你的问题中缺少了正确的标签。请看我的更新答案。 - Johannes Wanzek
3
很抱歉我漏了一个标记。我正在开发Windows8应用程序。你的解决方案是正确的,只需要添加一个小变化就可以了。我需要将UI_Boats数据上下文设置为theBoat,并且需要创建一个新的PropertyPath。this.UI_Boat.DataContext = this.theBoat; UI_Boat.SetBinding(Rectangle.WidthProperty, new Binding() { Path = new PropertyPath("Width"), Source = this.theBoat }); - beard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接