1

我有以下代碼:如何在Silverlight的ControlTemplate中訪問控件?

ControlTemplate ct = (ControlTemplate)XamlReader.Load(validXmlString); 

現在我需要獲得此模板創建的,於我而言,一個按鈕控制。我已經搜索了很多,找不到一個簡單的解釋如何做到這一點。

請注意,由於某些原因不明的原因,Microsoft爲WPF中的ControlTemplate提供了FindControl()方法,但在Silverlight中提供了而不是。我讀過這可以用VisualTreeHelper完成,但我還沒有看到如何解釋。

+0

你真的不應該這樣做...... – 2012-01-11 14:54:52

+0

無益響應,Silverlight是在其實施DataGrid的大量缺陷,而且它給我留下* *沒有選擇,只能做這個。你有如何做到這一點的知識?如果是這樣,請分享。 – 2012-01-11 14:59:29

+0

沒有選擇?也許你忽略了一些東西,你想要達到什麼樣的目標? – 2012-01-11 18:46:15

回答

1

下面您會發現一個遞歸循環遍歷Visual Tree並找到所有按鈕將其添加到集合的示例。你可以檢查按鈕的名稱等。並做你需要做的。我剛剛使用了一個集合作爲示例,因爲我發現了一個快速示例。

public MainPage() 
    { 
     InitializeComponent(); 
     this.Loaded += new RoutedEventHandler(MainPage_Loaded); 
    } 

    void MainPage_Loaded(object sender, RoutedEventArgs e) 
    { 
     List<UIElement> buttons = new List<UIElement>(); 

     GetChildren(this, typeof(Button), ref buttons); 
    } 

    private void GetChildren(UIElement parent, Type targetType, ref List<UIElement> children) 
    { 
     int count = VisualTreeHelper.GetChildrenCount(parent); 
     if (count > 0) 
     { 
      for (int i = 0; i < count; i++) 
      { 
       UIElement child = (UIElement)VisualTreeHelper.GetChild(parent, i); 
       if (child.GetType() == targetType) 
       { 
        //DO something with the button in the example added to a collection. You can also verify the name and perform the action you wish. 
        children.Add(child); 
       } 
       GetChildren(child, targetType, ref children); 
      } 
     } 
    } 

希望這有助於

相關問題