I have programmed an application that draws elements in a canvas. These elements are Rectangles (but I used the Border class because I want to instert text in it). These elements represent objects (Tasks in my case).
I draw these elements in code behind like this:
foreach (var task in TasksList)
{
var rect = new Border();
rect.Background = (SolidColorBrush)(new
BrushConverter().ConvertFrom("#0074D9"));
rect.BorderBrush = (SolidColorBrush)(new
BrushConverter().ConvertFrom("#001f3f"));
rect.BorderThickness = new Thickness(2);
rect.Width = 60;
rect.Height = 60;
var t = new TextBlock
{
Text = task.Id.ToString(),
Foreground = new SolidColorBrush(Colors.White),
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
rect.Child = t;
Canvas.SetLeft(rect, coordX);
Canvas.SetTop(rect, coordY);
Canvas.Children.Add(rect);
}
Insted of designing the border (rect) in code behind. I would like to design it as a XAML resource and create instances of this resources in code behind. How can accomplish this? How can I use bindings in this case? For instance, in the xaml resource I need to define that the property ID of the task needs to be binded to the Text property of a TextBlock placed in the middle of the border. But later, in the code behind, how do I specify the DataContext of the properties defined in the xaml?
Hope you could guide me. Thanks