2011年6月17日金曜日

【Silverlight】 指定の型のコントロール一覧を取得するには

List textBoxList
    = (from v in this.GetVisualOfType()
        select v).ToList();
using System;
using System.Windows;
using System.Windows.Media;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Linq;

namespace Extensions
{
    // DependencyObjectクラスの拡張メソッド
    public static class DependencyObjectExtensions
    {
        // 指定の型のコントロールを取得
        public static IEnumerable 
            GetVisualOfType(this DependencyObject obj)
        {
            return GetVisualTree(obj).Where(
                    element => element.GetType() == typeof(T)
                ).Cast();
        }

        // 子要素一覧を取得します。
        public static IEnumerable 
            GetVisualTree(this DependencyObject obj)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                var child = VisualTreeHelper.GetChild(obj, i);
                yield return child;

                foreach (var children in GetVisualTree(child))
                {
                    yield return children;
                }
            }
        }
    }
}

0 件のコメント:

コメントを投稿