How to programmatically set data binding using C# xaml

不打扰是莪最后的温柔 提交于 2019-12-07 18:43:53

问题


How do you programmatically set the DataContext and create a data binding in C# Xaml?

Given a Class

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

I am trying to programmatically set the Width of a Xaml Rectangle using data binding.

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

Where the Xaml look similar to this:

<Rectangle x:Name="UI_Boat" Fill="#FFF4F4F5" HorizontalAlignment="Center" Height="100" Stroke="Black" VerticalAlignment="Center" Width="{Binding}"/>

回答1:


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


来源:https://stackoverflow.com/questions/25112421/how-to-programmatically-set-data-binding-using-c-sharp-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!