找到可见的儿童窗口

时间:2012-08-03 03:03:17

标签: wpf

我想用这个简单的代码搜索任何可见的子窗口但是Message一直在说找不到Window。有人可以在主窗口中搜索可见的子窗口吗?

以下是代码:

private HomeWindow NewHomeWindow = new HomeWindow();
string ReturnWindowName;
private void btnhome_Click(object sender, RoutedEventArgs e)
{
    ReturnWindowName = "NewHomeWindow";
    NewHomeWindow.Owner = this;
    NewHomeWindow.Show();
}

private void btnsearchwindow_Click(object sender, RoutedEventArgs e)
{
    ChangeWindow();
}

public void ChangeWindow()
{
    Window mySearchWindow = (Window)this.FindName(ReturnWindowName);

    if (mySearchWindow != null)
    {
        MessageBox.Show("Window Found");
    }
    else
    {
        MessageBox.Show("Window Not Found");
    }
}

2 个答案:

答案 0 :(得分:0)

我不完全确定你的问题,但我认为你想找到一个控制的视觉孩子?

这是我经常使用的辅助函数..

public 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 (var window in FindVisualChildren<Window>(this))
{
  if (window.ReturnWindowName == <insertNameHere>)
     return window;
}

从那里,您可以遍历找到的窗口并匹配名称。

答案 1 :(得分:0)

由于您要为Windows分配所有权,您是否可以使用OwnedWindows属性来迭代通过父母拥有的Windows来查找您要查找的内容?在进一步查看代码时,您正在创建一个名为NewHomeWindow的类级别变量,您没有为Name属性分配任何内容,FindName正在搜索子元素,而不是拥有的窗口。如果您向窗口添加名称并使用类似的东西,您应该能够找到它。

public partial class MainWindow : Window
{
    private HomeWindow NewHomeWindow = new HomeWindow(); 
    string ReturnWindowName;
    public MainWindow()
    {
        InitializeComponent();

        NewHomeWindow.Name="NewHomeWindow";
    }

    private void btnhome_Click(object sender, RoutedEventArgs e) 
    {
        ReturnWindowName = "NewHomeWindow";
        NewHomeWindow.Owner = this;
        NewHomeWindow.Show();
    }

    private void btnsearchwindow_Click(object sender, RoutedEventArgs e)
    {
        ChangeWindow(); 
    }

    public void ChangeWindow()
    {
        foreach (Window w in this.OwnedWindows)
        {
            if (w.Name == ReturnWindowName)
            {
                MessageBox.Show("Window Found");
            }
            else
            {
                MessageBox.Show("Window Not Found");
            }
        }
    }
}