我有一些 Silverlight 4 UI 对象(更像是导航页面)必须实现两件事:OnError 事件处理程序和 Refresh() 方法。
所以我尝试了以下方法:
public interface IDynamicUI
{
event EventHandler<ErrorEventArgs> OnError;
void Refresh();
}
public class ErrorEventArgs : EventArgs
{
public string Message { get; set; }
public Exception Error { get; set; }
}
但是编译器给我的错误是不能在公共(public)接口(interface)中声明字段。
好吧,问题在于应该实现此功能的页面托管在导航框架内,采用 SL4 导航框架。这很好,但是,我还需要能够将子页面内发生的事件(如错误)中继到父页面。此外,我希望能够根据父页面中发生的事件强制刷新子页面 UI。
为了避免使用反射(查看导航面板中显示的页面类型),我只想从中提取 IDynamic UI。这将允许我做这样的事情:
public class ParentPage : Page
{
IDynamicUI selectedUI = null;
//fires when the ChildContent frame loads a child page...
private void ChildContentFrame_Navigated(object sender, NavigationEventArgs e)
{
object childPage = ChildContentFrame.Content;
this.selectedUI = (IDynamicUI)childPage;
this.selectedUI.OnError += new EventHandler(ChildPage_OnError);
}
private void ChildPage_OnError(object sender, ErrorEventArgs e)
{
//do my error handling here.
}
}
对于所有喜欢 MVVM/MVC 的人...好吧,不是这样。我确实知道,如果采用 MVVM 方法来制作它,它会容易得多,但是该应用程序已经编写完毕,我不打算从头开始重写它。 :(
谢谢 马丁
最佳答案
Create a interface IInform
public interface IInform
{
event EventHandler Inform;
void InformNow();
}
Create a Class ImplementIInform
public class ImplementInform : IInform
{
public event EventHandler Inform;
public void InformNow()
{
OnInformed(new EventArgs());
}
private void OnInformed(EventArgs eventArgs)
{
if (Inform != null)
{
Inform(this, eventArgs);
}
}
}
Create a Console Application like below..
static void Main(string[] args)
{
IInform objInform = new ImplementInform();
objInform.Inform +=new EventHandler(Informed);
objInform.InformNow();
Console.ReadLine();
}
private static void Informed(object sender, EventArgs e)
{
Console.WriteLine("Informed");
}
Output: Informed
关于c# - 如何在接口(interface)中声明事件处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7824771/