2011-03-20 96 views
2

使用Miguel de Icaza的Patterns for Creating UITableViewCells,我创建了一个自定义的UITableViewCell,并将其转换为MonoTouch.Dialog元素。我正在使用元素API来创建编辑表单,并使用我的一些自定义元素。MonoTouch.Dialog:元素删除事件

我想弄清楚如何响应元素的删除。我的自定义元素引用了它在数据库中表示的记录。我想以同样的方式响应已删除的事件,我将响应Selected事件,在那里获得DialogViewController,UITableView和NSIndexPath。假设我可以响应的元素存在这样的事件,我会用给定的记录ID向数据库发出删除语句。

回答

3

您将不得不修改源以处理Source类中的删除事件,并将该消息分发给元素,方式与为其他事件完成相同。

4

基于Miguel的回答,我将一个公共Delete方法添加到名为MyDataElement的子类Element中。

public class MyDataElement : Element { 
    static NSString key = new NSString ("myDataElement"); 
    public MyData MyData; 

    public MyDataElement (MyData myData) : base (null) 
    { 
      MyData = myData; 
    } 

    public override UITableViewCell GetCell (UITableView tv) 
    { 
      var cell = tv.DequeueReusableCell (key) as MyDataCell; 
      if (cell == null) 
       cell = new MyDataCell (MyData, key); 
      else 
       cell.UpdateCell (MyData); 
      return cell; 
    } 

    public void Delete() { 
     Console.WriteLine(String.Format("Deleting record {0}", MyData.Id)); 
    } 
} 

然后在我的子归DialogViewController,我处理CommitEditingStyle方法中,将元素MyDataElement,然后调用Delete方法:

public class EntityEditingSource : DialogViewController.Source { 

      public EntityEditingSource(DialogViewController dvc) : base (dvc) {} 

      public override bool CanEditRow (UITableView tableView, NSIndexPath indexPath) 
      { 
       // Trivial implementation: we let all rows be editable, regardless of section or row 
       return true; 
      } 

      public override UITableViewCellEditingStyle EditingStyleForRow (UITableView tableView, NSIndexPath indexPath) 
      { 
       // trivial implementation: show a delete button always 
       return UITableViewCellEditingStyle.Delete; 
      } 

      public override void CommitEditingStyle (UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath) 
      { 
       // In this method, we need to actually carry out the request 
       var section = Container.Root [indexPath.Section]; 
       var element = section [indexPath.Row]; 

       //Call the delete method on MyDataElement 
       (element as MyDataElement).Delete(); 
       section.Remove (element); 
      } 

     }