简体   繁体   English

重绘 WPF 控件(图像控件)时如何引发事件?

[英]How do I raise an event when a WPF control ( Image control) is redrawn?

I have a winforms paint event handler that handles the paint event for a picturebox.我有一个处理图片框的绘制事件的 winforms 绘制事件处理程序。 As the paint event description says, "...the event is fired when the control is redrawn".正如绘制事件描述所说,“...重绘控件时会触发该事件”。 I do not quite understand this and I wish to raise the same event in WPF on an Image control.我不太明白这一点,我希望在 WPF 中的 Image 控件上引发相同的事件。 But I can't find any such events.但我找不到任何此类事件。 Here is the winforms code这是winforms代码

How do I do this in WPF??我如何在 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));
        }
    }
}

I have already converted all the code within the event Hanlder to WPF using DrawingContext class.我已经使用 DrawingContext 类将事件 Hanlder 中的所有代码转换为 WPF。 Now, I only need help on the event that I can raise "when the Image control is redrawn".现在,我只需要有关“重绘 Image 控件时”可以引发的事件的帮助。

WPF doesn't use WinForm's on-demand mode painting. WPF 不使用 WinForm 的按需模式绘制。 The OnRender method of a UIElement is called by the layout system whenever it wants the element to "redraw" itself.每当布局系统希望元素“重绘”自身时,就会调用UIElementOnRender方法。 You can override this method in your class:您可以在类中覆盖此方法:

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

If you want to re-render the element explicitly you could call the InvalidateVisual() method.如果要显式重新渲染元素,可以调用InvalidateVisual()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM