我正在尝试将一个事件注册到 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");
}
}
WP8帆布.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,但当然会发生空异常。这是我的线程t控制WP8Canvas对象的创建,但这发生在运行时,我不知道什么时候。
问:如何将我的WP8Canvas重绘事件注册到主页而不会遇到空指针异常。
如果您无法控制 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 声明为静态,并分配您存储的事件处理程序:
public static WP8Canvas CurrentWP8Canvas
{
get
{
return CurrentCanvas as WP8Canvas;
}
set
{
CurrentCanvas = value;
value.Redraw += RedrawCanvas;
}
}
它应该有效。但是,由于多种原因,这是非常错误的:线程同步问题,内存泄漏的风险......在这一点上,你应该得出结论,你已经走到了死胡同,回溯,并考虑重新设计你的架构。