WPFのメモ

■子ウィンドウを取得

using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using C1.WPF.Docking; // C1DockTabItem の名前空間

namespace YourNamespace
{
    public partial class DPFWindow : Window
    {
        public DPFWindow()
        {
            InitializeComponent();
        }

        private void CheckWrapPanelAndFindDockTabItem()
        {
            // DPFWindow の子階層から WrapPanel を検索
            var wrapPanel = FindChild<WrapPanel>(this);
            if (wrapPanel != null)
            {
                // WrapPanel の中にある C1DockTabItem を検索
                var dockTabItems = FindChildren<C1DockTabItem>(wrapPanel);
                foreach (var dockTabItem in dockTabItems)
                {
                    MessageBox.Show($"C1DockTabItem found: {dockTabItem.Name}");
                }
            }
            else
            {
                MessageBox.Show("WrapPanel not found in DPFWindow.");
            }
        }

        // ボタンから呼び出す例
        private void OnCheckButtonClick(object sender, RoutedEventArgs e)
        {
            CheckWrapPanelAndFindDockTabItem();
        }

        // 子コントロールを再帰的に検索(1つだけ見つける)
        private T FindChild<T>(DependencyObject parent) where T : DependencyObject
        {
            if (parent == null) return null;

            int childCount = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < childCount; i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);

                if (child is T target)
                    return target;

                var result = FindChild<T>(child);
                if (result != null)
                    return result;
            }

            return null;
        }

        // 子コントロールを再帰的に検索(複数を取得)
        private IEnumerable<T> FindChildren<T>(DependencyObject parent) where T : DependencyObject
        {
            if (parent == null) yield break;

            int childCount = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < childCount; i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);

                if (child is T target)
                    yield return target;

                foreach (var descendant in FindChildren<T>(child))
                {
                    yield return descendant;
                }
            }
        }
    }
}

コメント

タイトルとURLをコピーしました