2014-12-02 145 views
0

我發現的方法來從用戶控件訪問主窗口:訪問控制

  • 窗口parentWindow = Window.GetWindow(本);
  • DependencyObject parentWindow = VisualTreeHelper.GetParent(child);
  • Application.Current.MainWindow as parentWindow;

我有一些問題:

  1. 其中上述方法是最好的?
  2. 如何在主窗口中從usercontrol訪問usercontrol中的控件,並在同一主窗口中訪問usercontrol和usercontrol中的控件?

感謝, 跳過我的英語不好:)

回答

2

Current.MainWindow是在任何情況下理想的,因爲如果UserControl被嵌入到另一個UserControl,你仍然可以使用Current.MainWindow向上遍歷樹。所有的方法都很好,這一切都取決於使用情況和你想要完成的。

要訪問UserControl內的控件(可以說TextBlock)。

TextBlock tb = FindVisualChildren<TextBlock>(usercontrol) 

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

無建議是「最好的」:

Application.Current.MainWindowWindow.GetWindow(this): 並不好,因爲你與常見的設計模式和規則(如「原則,依賴倒置」或MVVM)打破

使用VisualTreeHelper在編碼XAML轉換器(這些直接處理UI的元素)時有時很有用。由於你強烈依賴於你的xaml可視化樹,所以在代碼中不太可取。

如果你想在MainWindowUserControl之間的溝通,保持對其他組件上可重複使用UserControl,添加一個或多個dependency properties你的用戶控件,並在XAML中設置的綁定。

如果你想快速簡單的測試應用程序,確保Application.Current.MainWindow仍然是一個不錯的選擇。