【问题标题】:c# set active menu on a tree list from bottom upc#从下往上在树列表上设置活动菜单
【发布时间】:2015-09-17 04:57:11
【问题描述】:

我有一堂课:

public class Menu
{
     public Menu()
     {
          this.Children = new List<Menu>();
     }

     public string MenuId { get; set; }
     public string Title { get; set; }
     public bool IsActive { get; set; }
     public List<Menu> Children { get; set; }    
}

现在我有一个列表:

List<Menu> menu = new List<Menu>();

假设一个 MenuId 为 20,我如何将属性 IsActive 递归设置为 MenuId = 20 的菜单的所有父级?

这是我的尝试:

  List<Menu> menu = new List<Menu>

        foreach (Menu _menu in menu)
        {
            if (_menu.MenuId == _id)
            {
                _menu.IsActive = true;
                break;
            }
            else
            {
                SetActive(_menu, _id);
            }
        }

    private void SetActive(Menu menu, string _id)
    {
        foreach (Menu _menu in menu.Children)
        {
            if (_menu.MenuId == targetContentId)
            {
                _menu.IsActive = true;
                break;
            }
            else
            {
                SetActive(_menu, _id);
            }
        }
    }

【问题讨论】:

  • 应该IsActive 是bool?
  • 向下递归直到找到匹配项,然后在展开时设置IsActive。
  • @DaveZych:是的,它是布尔值。我的错。
  • @MattBurland:实际上我是这样做的(我添加了示例代码)。问题是我不知道如何为该项目的父母设置 IsActive。所以现在当我找到该项目时,我如何从下向上遍历它以便为它的所有父项设置 IsActive 直到根项目?
  • 还可以考虑使用访问者模式:stackoverflow.com/questions/6586586/…

标签: c# list tree


【解决方案1】:

类似这样的东西(假设 id 在整个结构中是唯一的):

bool FindAndSet(int id, List<Menu> menu)
{
    foreach (var m in menu)
    {
        if (m.MenuId == id)    // base case, this is the item we are looking for
        {
            m.IsActive = true;
            return true;
        }
        else if (m.Children == null || m.Children.Count == 0)
        {
            return false;    // other base case, no more children
        }
        var found = FindAndSet(id, m.Children);    // recurse
        if (found)                                 // if we found it in our descendants
        {
            m.IsActive = true;                     // set is active as we unwind
            return true;
        }
    }
    return false;
}

【讨论】:

  • 只是一个小评论:我将return false; // other base case, no more children 替换为continue; 否则在树的第一个分支上,如果没有更多的孩子,它将停止。
【解决方案2】:

让Menu 有一个事件(例如,它可以实现INotifyPropertyChanged,但它也可以有一个更强类型的IsActiveChanged 事件)。

每当IsActive 更改时引发该事件。

让所有父母订阅他们直系子女的事件,并相应地更新他们自己的IsActive 值。

【讨论】:

  • 听起来不错,我以前从未使用过 INotifyPropertyChanged。我可以试一试。为什么不呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-19
  • 1970-01-01
  • 2017-11-10
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
相关资源
最近更新 更多