Reputation: 91
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}"/>
Upvotes: 3
Views: 10366
Reputation: 2875
this.UI_Boat.SetBinding(Rectangle.WidthProperty, new Binding()
{
Path = "Width",
Source = theBoat
});
Upvotes: 6