Or you can use direct positioning on the canvas if you prefer direct control over the position of the drawing:
My example defines a user interface control that draws rectangles with text in it:
XAML:
<UserControl x:Class="DrawOnCanvase" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:MySample" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"> <Grid> <Canvas x:Name="DrawCanvas" Height="30"/> </Grid>
Code behind:
// You might eg call this in the constructor of DrawOnCanves internal void DrawRectWithText() { var rect = new System.Windows.Shapes.Rectangle(); rect.Stroke = new SolidColorBrush(Colors.Black); rect.Fill = new SolidColorBrush(Colors.Beige); rect.Width = 100; rect.Height = 100; // Use Canvas static methods to position the rectangle Canvas.SetLeft(rect, 100); Canvas.SetTop(rect, 100); var text = new TextBlock() { Text = task.Title, }; // Use Canvas static methods to position the text Canvas.SetLeft(text, 90); Canvas.SetTop(text, 90); // Draw the rectange and the text to my Canvas control. // DrawCanvas is the name of my Canvas control in the XAML code DrawCanvas.Children.Add(rect); DrawCanvas.Children.Add(text); }
source share