You make a rectangle and add it to the canvas' children.
var myRect = new System.Windows.Shapes.Rectangle();
myRect.Stroke = System.Windows.Media.Brushes.Black;
myRect.Fill = System.Windows.Media.Brushes.SkyBlue;
myRect.HorizontalAlignment = HorizontalAlignment.Left;
myRect.VerticalAlignment = VerticalAlignment.Center;
myRect.Height = 50;
myRect.Width = 50;
myParentCanvas.Children.Add(myRect);
I suspect that using WPF drawing techniques is faster than GDI+ simply because WPF can take advantage of the graphics card to do drawing, as opposed to GDI+ which is bitmap based.
(I have not personally measured them though)
If you really want to use GDI+ like techniques, you can look into using a WPF image control, DrawingVisual, and RenderTargetBitmap as shown here:
<Grid>
<Image Name="Background"
Width="200"
Height="200"
VerticalAlignment="Center"
HorizontalAlignment="Center" />
</Grid>
Code-behind for the window:
private RenderTargetBitmap buffer;
private DrawingVisual drawingVisual = new DrawingVisual();
public MainWindow()
{
InitializeComponent();
}
protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
buffer = new RenderTargetBitmap((int)Background.Width, (int)Background.Height, 96, 96, PixelFormats.Pbgra32);
Background.Source = buffer;
DrawStuff();
}
private void DrawStuff()
{
if (buffer == null)
return;
using (DrawingContext drawingContext = drawingVisual.RenderOpen())
{
drawingContext.DrawRectangle(new SolidColorBrush(Colors.Red), null, new Rect(0, 0, 10, 10));
}
buffer.Render(drawingVisual);
}
(stolen from
StackOverflow)
If you
really want to use GDI+ itself, you could also look into
hosting a Windows Forms control in WPF and drawing on it.