0

我想用这个简单的代码搜索任何可见的子窗口,但消息一直说找不到窗口。任何人都可以知道在主窗口中搜索可见子窗口吗?

这是代码:

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");
    }
}
4

2 回答 2

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;
}

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

于 2012-08-03T03:11:03.930 回答
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");
            }
        }
    }
}
于 2012-08-03T03:14:34.283 回答