Painting on MainWindow in WPF

I am trying to paint on my MainWindow. I am using this sample code:

MainWindow.xaml.cs

namespace WpfApplication4
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            Trace.WriteLine("OnRender");

            drawingContext.DrawRectangle(Brushes.Red, new Pen(Brushes.Black, 5), new Rect(20, 20, 250, 250));

            base.OnRender(drawingContext);
        }
    }
}

MainWindow.xaml

<Window x:Class="WpfApplication4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="400" Width="600">
</Window>

The message "OnRender" appears in the output window, but nothing is drawn. MainWindow and Output

What am I doing wrong?

+3
source share
1 answer

Install Background="Transparent"in the XAML window.

And always call base.OnRenderin front of your own drawings, since you want to draw base class drawings (if any).

+5
source

All Articles