3

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}"/>
beard
  • 91
  • 1
  • 2
  • 13
  • I know it's _not_ what you asked, but what's wrong with `` ? – Tzah Mama Aug 04 '14 at 05:51
  • @TzahMama Adding that to the Xaml and Changing the Height="100" showed the correct behavior; care to explain? – beard Aug 04 '14 at 06:20
  • 1
    Well `Binding Path="Something"` goes to your `DataContext` and searches for `Something` property. If one is found (and is acceptable with the type that required) it will be used as value. You can even go for properties of properties `Path=Something.SomeNumber` – Tzah Mama Aug 04 '14 at 06:32

1 Answers1

6
 this.UI_Boat.SetBinding(Rectangle.WidthProperty, new Binding()
            {
                Path = "Width",
                Source = theBoat
            });
Johannes Wanzek
  • 2,825
  • 2
  • 29
  • 47
  • Error: 'Windows.UI.Xaml.Data.Binding' does not contain a constructor that takes 1 arguments This is in reference to the, new Binding("Width") – beard Aug 04 '14 at 06:24
  • Are you developing for WP8? You missed the correct Tag in your question. See my updated answer. – Johannes Wanzek Aug 04 '14 at 06:28
  • 3
    Sorry for missing a tag. I am developing a Windows8 App. Your solution is correct with one addition and a minor change. I needed to set the UI_Boats DataContext to theBoat. And I needed to make a new PropertyPath `this.UI_Boat.DataContext = this.theBoat; UI_Boat.SetBinding(Rectangle.WidthProperty, new Binding() { Path = new PropertyPath("Width"), Source = this.theBoat });` – beard Aug 05 '14 at 03:03