Xamarin.iOS 封装委托事件

来源:互联网 发布:淘宝店铺搜索页装修 编辑:程序博客网 时间:2024/05/17 05:17

前些天写的博客,自定义了一个组合view,由于对c#的事件机制不了解,所以view中的按钮回调Controller的方式我选择了开发Android时常使用的接口回调。在同事指出问题后我查阅了一些资料,看了几本书中c#委托机制的资料。最后封装了一下委托事件总线,java慢慢也在模仿这种委托机制。

下面贴出封装的类以及使用方法。

先贴出封装的委托机制的类:

using System;namespace RuilaiGrow.iOS{/// <summary>/// 委托事件总线 基类/// by ge/// </summary>public class EventBus : EventArgs{public EventBus(string bus){this.Bus = bus;}public string Bus { get; set; }}public class EventBusDealer {public event EventHandler<EventBus> NewBusInfo;public void NewBus(object sender, string bus) {RaiseNewBusInfo(sender, bus);}protected void RaiseNewBusInfo(object sender, string bus){EventHandler<EventBus> newBusInfo = NewBusInfo;if (newBusInfo != null) {newBusInfo(sender, new EventBus(bus));}}}}


在贴出使用方法,举例子,场景:假如现在在我自定义的view中有一个按钮,在他的点击事件中回调到界面几个数据。

第一步,在自定义的view中实例化封装的话委托事件对象:

//委托事件public EventBusDealer eventBus = new EventBusDealer();
在点击事件中:

Button.TouchUpInside += (sender, e) =>{eventBus.NewBus(_list[index], "");};

在界面Controller中使用view找到委托事件的对象并绑定事件:

ListView.eventBus.NewBusInfo += (object sender, EventBus e) => { //事件发送到这里};

上面我封装的EventBus(Android我一直使用的就是EventBus,所以从情怀的角度起名叫这个,不要误导大家。我自己写iOS的demo时候,程序的icon一直用的是Android的小机器人图标,哈哈哈)发送的第二个参数是String,可以自行修改达到自己的需求。






1 0
原创粉丝点击