首页 > 解决方案 > 重绘 WPF 控件(图像控件)时如何引发事件?

问题描述

我有一个处理图片框的绘制事件的 winforms 绘制事件处理程序。正如绘制事件描述所说,“......当重绘控件时触发事件”。我不太明白这一点,我希望在 WPF 中的 Image 控件上引发相同的事件。但我找不到任何此类事件。这是winforms代码

我如何在 WPF 中做到这一点?

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    if (pictureBox1.Image != null)
    {
        if (temprect != new Rectangle())
        {
            e.Graphics.DrawRectangle(new Pen(selectionBrush, 2), temprect);
        }
    }
    else
    {
        using (Font myFont = new Font("Arial", 40, FontStyle.Bold))
        {
            e.Graphics.DrawString("No Image", myFont, Brushes.LightGray,
                new Point(pictureBox1.Width / 2 - 132, pictureBox1.Height / 2 - 50));
        }
    }
}

我已经使用 DrawingContext 类将事件 Hanlder 中的所有代码转换为 WPF。现在,我只需要对可以引发“重绘图像控件时”的事件的帮助。

标签: c#wpfwinformspaintevent

解决方案


WPF 不使用 WinForm 的按需模式绘画。每当布局系统希望元素“重绘”自身时,都会调用a的OnRender方法。UIElement你可以在你的类中重写这个方法:

public class YourElement : FrameworkElement
{
    protected override void OnRender(DrawingContext dc)
    {
        base.OnRender(dc);
    }
}

如果要显式重新渲染元素,可以调用该InvalidateVisual()方法。


推荐阅读