簡體   English   中英

是否可以通過指定TableSection的名稱來刪除並附加在TableSection之后?

[英]Can I remove and append after a TableSection by specifying the name of that TableSection?

我有一個應用程序,我經常刪除tableSections並將其替換為另一個。 這是我使用的典型代碼:

  • TableSection 0-稱為“標題”
  • 表第1部分-稱為“組”
  • 表格2-稱為“卡片”

    如果(tableView.Root.Count> 2)tableView.Root.RemoveAt(2); //刪除名為“ Cards”的部分tableView.Root.Add(CreateTableSection());

我想使代碼更簡潔。 有沒有一種方法可以通過使用分配給該節的名稱來刪除tableSection,還可以在命名節后追加?

var header = tableView.Root.FirstOrDefault(r => r.Title == "Header");

if (header != null) {
  tableView.Root.Remove(header);
}

或者,您可以在創建標題部分時僅保留對其的引用,然后使用該引用稍后將其刪除。 這使您不必在刪除它之前就找到它。

您可以為TabelRoot創建擴展方法, TabelRoot代碼更TabelRoot

擴展方式

public static class Extensions
{
    public static TableSection FindSection(this TableRoot root, string title)
    {
        return root.FirstOrDefault(r => r.Title == title);
    }

    public static bool AppendAfter(this TableRoot root, string title, TableSection toBeAdded)
    {
        var section = root.FindSection(title);
        if (section != null)
        {
            var index = root.IndexOf(section);
            root.Insert(index + 1, toBeAdded);
        }
        return false;
    }

    public static bool AppendBefore(this TableRoot root, string title, TableSection toBeAdded)
    {
        var section = root.FindSection(title);
        if (section != null)
        {
            var index = root.IndexOf(section);
            root.Insert(index, toBeAdded);
        }
        return false;
    }

    public static bool Remove(this TableRoot root, string title)
    {
        var section = root.FindSection(title);
        if (section != null)
            return root.Remove(section);
        return false;
    }

    public static bool Replace(this TableRoot root, TableSection newSection)
    {
        var section = root.FindSection(newSection?.Title);
        if (section != null)
        {
            var index = root.IndexOf(section);
            root.RemoveAt(index);
            root.Insert(index, newSection);
        }
        return false;
    }
}

用法

var root = tableView.Root;
root.Remove("Section 2");
root.AppendAfter("Section 1", toBeAdded: section4 });
root.AppendBefore("Section 2", toBeAdded: section0 });
root.AppendBefore("Section 4", toBeAdded: new TableSection { Title = "Section 3" });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM