开发者

Simple WPF Custom Control - How to set background color?

开发者 https://www.devze.com 2022-12-15 06:04 出处:网络
I\'ve created the simplest possible WPF control - It just overrides OnRender and draws a red rectangle.

I've created the simplest possible WPF control - It just overrides OnRender and draws a red rectangle.

开发者_如何学Go

However only when setting the Background in XAML to Blue, the control is all blue with no red showing. If Background is not set, the red rectangle shows no problem.

How come the red rectangle is not displayed over the blue background when the background is set?

public class MyWpfControl : Control
{
    protected override void OnRender(DrawingContext drawingContext)
    {
        drawingContext.DrawRectangle(Brushes.Red, null, new Rect(0, 0, 100, 100));
    }
}


Because OnRender is done first, then the background is rendered - unless you're writing a very performance-intensive control, you do not need to override OnRender ever.

Check out Adam Nathan's book "WPF Unleashed" - it will get you started with the right way of writing controls and give a great introduction to WPF. Leave your Winforms knowledge at the door, things are very different, it's a separate way of thinking than the Winforms/Win32 approach.


No sure how did you get the problem. Below is a simple app which takes use of MyWpfControl and it works fine. Hope it will be helpful even though the problem cannot be reproduced. Good luck.

namespace MyWpfControlDemo
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            WPFControl = new MyWpfControl();
            this.DataContext = this;
        }

        public MyWpfControl WPFControl { get; set; }
    }
}

The code in xaml.

<Window x:Class="MyWpfControlDemo.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <UserControl Content="{Binding WPFControl}"/>
    </Grid>
</Window>


Remove you setting background Red, and in the overriding method OnRender add this:

drawingContext.DrawRectangle(Brushes.Red,null,new Rect(new Point(0,0),this.RenderSize)); // background
0

精彩评论

暂无评论...
验证码 换一张
取 消