Skip to main content
 首页 » 编程设计

c#之MonoTouch.Dialog RootElement 的自定义标题

2024年02月20日13unruledboy

我正在尝试使用 Monotouch.Dialog 构建菜单结构。该结构由多个嵌套的 RootElement 组成。

创建 RootElement 时,您在构造函数中设置标题。此标题用于表格单元格的文本以及单击它后出现的 View 中的标题。

我想将 View 的标题设置为与元素名称不同的文本。

让我试着用一个简化的例子来说明我的意思。

结构:

- Item 1 
  - Item 1.1 
  - Item 1.2 
- Item 2 
  - Item 2.1 

创建此结构的代码:

[Register ("AppDelegate")] 
public partial class AppDelegate : UIApplicationDelegate 
{ 
    UIWindow _window; 
    UINavigationController _nav; 
    DialogViewController _rootVC; 
    RootElement _rootElement; 
 
    public override bool FinishedLaunching (UIApplication app, NSDictionary options) 
    { 
        _window = new UIWindow (UIScreen.MainScreen.Bounds); 
 
        _rootElement = new RootElement("Main"); 
 
        _rootVC = new DialogViewController(_rootElement); 
        _nav = new UINavigationController(_rootVC); 
 
        Section section = new Section(); 
        _rootElement.Add (section); 
 
        RootElement item1 = new RootElement("Item 1"); 
        RootElement item2 = new RootElement("Item 2"); 
 
        section.Add(item1); 
        section.Add(item2); 
 
        item1.Add   ( 
                        new Section() 
                        { 
                            new StringElement("Item 1.1"), 
                            new StringElement("Item 1.2") 
                        } 
                    ); 
 
        item2.Add (new Section() {new StringElement("Item 2.1")}); 
 
        _window.RootViewController = _nav; 
        _window.MakeKeyAndVisible (); 
 
        return true; 
    } 
} 

单击项目 1 时,将显示标题为“项目 1”的屏幕。我想将标题“项目 1”更改为“类型 1 项目”。但是被点击的元素的文本应该保持为“Item 1”。

处理这个问题的最佳方法是什么?

如果我能做这样的事情就好了:

RootElement item1 = new RootElement("Item 1", "Type 1 items"); 

我尝试获取 DialogViewController(参见 this 帖子)并设置它的标题。但我没能让它正常工作。

请您参考如下方法:

您可以创建 RootElement 的子类,它会覆盖 GetCell 的返回值,并在它是 TableView 的一部分时更改要呈现的文本:

 class MyRootElement : RootElement { 
      string ShortName; 
 
      public MyRootElement (string caption, string shortName) 
          : base (caption) 
      { 
          ShortName = shortName; 
      } 
 
      public override UITableViewCell GetCell (UITableView tv) 
      { 
           var cell = base.GetCell (tv); 
           cell.TextLabel.Text = ShortName; 
           return cell; 
      } 
 }