将事件附加到类

时间:2013-09-09 07:52:18

标签: c# events event-handling windows-phone

我正在尝试将事件注册到 MainPage.xaml.cs ,如下所示:

public partial class MainPage : PhoneApplicationPage
{

public static ICanvas CurrentCanvas;


private void MainPage_Loaded(object sender, RoutedEventArgs e)
    {

    //HERE I TRY TO REGISTER FOR MY EVENT

    ((WP8Canvas)CurrentCanvas).Redraw += WP8EventHandler_RedrawCanvas;

    //HERE I TRY TO REGISTER FOR MY EVENT/

    System.Threading.ThreadStart start = new System.Threading.ThreadStart(launchProcessA);
    System.Threading.Thread t = new System.Threading.Thread(start);
    t.Name = "ProcessA Thread";
    t.Start();

    }

    /// <summary>
    /// Listen to WP8Canvas repaint() methods
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    public void WP8EventHandler_RedrawCanvas(object sender, EventArgs e)
    {
        wpCanvas.InvalidateArrange();
        Debug.WriteLine("Redraw Canvas Event"); 
    }

}

WP8Canvas.cs

public class WP8Canvas : WP8Displayable, ICanvas
{
    public Canvas canvas ;
    public event EventHandler Redraw;
    protected object reference;


    public WP8Canvas(object reference)
    {
        this.reference = reference;
        MainPage.CurrentCanvas = this;
        Debug.WriteLine("WP8Canvas instance");
    }

    public void repaint()
    {            
        RedrawCanvas();
    }

    /// <summary>
    /// Raise event if repaint() method is hit
    /// </summary
    private void RedrawCanvas()
    {
        //Null check makes sure the main page is attached to the event
        if (this.Redraw != null)
            this.Redraw(new object(), new EventArgs());
    }

}

在我的评论之间 //在这里我尝试注册我的活动我尝试注册一个非实例化的对象 WP8Canvas 但当然会发生null异常。控制 WP8Canvas 对象的创建是 Thread t ,但这在运行期间发生,我不知道何时发生。

问题:如何将 WP8Canvas 重绘事件注册到 MainPage ,而不会遇到空指针异常。

1 个答案:

答案 0 :(得分:1)

如果您无法控制launchProcessA,那么达到此结果的方法是使用属性:

public WP8Canvas CurrentWP8Canvas
{
    get
    {
        return this.CurrentCanvas as WP8Canvas;
    }

    set
    {
        this.CurrentCanvas = value;
        value.Redraw += WP8EventHandler_RedrawCanvas;
    }    
}

然后您必须更改代码,以便线程分配CurrentWP8Canvas属性而不是CurrentCanvas

编辑:如果您需要它是静态的,一种方法是将事件处理程序存储在临时静态变量中:

public static EventHandler RedrawCanvas { get; set; }

然后从MainPage的构造函数中设置它:

RedrawCanvas = WP8EventHandler_RedrawCanvas;

最后,将CurrentWP8Canvas声明为static,并分配您存储的事件处理程序:

public static WP8Canvas CurrentWP8Canvas
{
    get
    {
        return CurrentCanvas as WP8Canvas;
    }

    set
    {
        CurrentCanvas = value;
        value.Redraw += RedrawCanvas;
    }    
}

它应该工作。然而,由于许多原因,这是非常错误的:线程同步问题,内存泄漏的风险......在这一点上,你应该得出结论,你已经达到了死胡同,回溯并考虑重新设计你的架构。 / p>