【问题标题】:select objects dynamically in code在代码中动态选择对象
【发布时间】:2015-06-24 15:30:26
【问题描述】:

我有一个包含 40 个矩形(4x10 网格)的 xaml 页面,所有矩形都以 r1-1 到 r10-4 的格式命名。

我想在代码中遍历这些:

        for (int row = 1; row < 10; row++)
        {
            for (int col = 1; col < 4; col++)
            {
                 ...// what do I need here
            }
        }

有什么帮助吗?

【问题讨论】:

  • 您可以使用 VisualTreeHelper 来查找控件。 msdn.microsoft.com/en-us/library/…
  • 您是否尝试使用 FindName() 方法:this.FindName("r"+row+"-"+col) ?
  • @Cubi 谢谢...我怎么错过了!
  • 不客气。我用这种方法发布了一个答案。

标签: c# xaml windows-phone


【解决方案1】:

虽然我不建议这样做,但您可以简单地遍历 Grid Panel 中的所有项目,如果您有它的引用。试试这样的:

foreach (UIElement element in YourGrid.Children)
{
    // do something with each element here
}

【讨论】:

  • 这里有一个很好的推荐。仅通过必要的控制进行迭代。
【解决方案2】:

您可以使用以下方法通过名称动态获取元素:

for (int row = 1; row < 10; row++)
{
    for (int col = 1; col < 4; col++)
    {
        var elt = this.FindName("r" + row + "-" + col);
        // do some stuff
    }
}

【讨论】:

    【解决方案3】:

    您可以按类型或名称找到您的控件:

    按类型

    public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
    {
        if (depObj != null)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                if (child != null && child is T)
                {
                    yield return (T)child;
                }
    
                foreach (T childOfChild in FindVisualChildren<T>(child))
                {
                    yield return childOfChild;
                }
            }
        }
    }
    

    然后你可以遍历可视化树:

    foreach (Rectangle r in FindVisualChildren<Rectangle>(window))
    {
        // do something with r here
    }
    

    按名称

    for (int row = 1; row < 10; row++)
    {
        for (int col = 1; col < 4; col++)
        {
            var control = this.FindName(string.Format("r{0}-r{1}", row.ToString(), col.ToString()));    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-29
      • 2013-06-29
      • 1970-01-01
      • 2012-10-04
      • 1970-01-01
      • 1970-01-01
      • 2011-03-30
      相关资源
      最近更新 更多