2013-03-06 64 views
0

WPF XAML訪問自定義控制我有一個DataTemplate自定義控件`AutoCompleteTextBox如下圖所示:中的DataTemplate

<DataGridTextColumn.HeaderTemplate> 
    <DataTemplate> 
    <StackPanel Orientation="Vertical"> 
     <TextBlock 
           Text="{Binding Content, RelativeSource={RelativeSource Mode=TemplatedParent}}" 
           Margin="5" /> 

     <Border DockPanel.Dock="Top" 
            HorizontalAlignment="Left" 
            VerticalAlignment="Center" 
            Padding="2"> 

      <uc:AutoCompleteTextBox x:Name="AutoTextBox" /> 

     </Border> 
    </StackPanel> 
    </DataTemplate> 
</DataGridTextColumn.HeaderTemplate> 

我怎麼能在代碼中訪問AutoTextBox的背後?

回答

0

無法直接按名稱訪問DataTemplate中的控件!但你可以嘗試讓VisualTree ...

DependencyObject dgColumnHeader = GetYourColumnHeader(); 
var yourAutoCompleteTextBox = FindVisualChild<AutoCompleteTextBox>(dgColumnHeader); 


public static T FindVisualChild<T>(DependencyObject parent) where T : DependencyObject 
{ 
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++) 
    { 
     DependencyObject child = VisualTreeHelper.GetChild(parent, i); 
     if (child != null && child is T) 
      return (T)child; 
     else 
     { 
      T childOfChild = FindVisualChild<T>(child); 
      if (childOfChild != null) 
       return childOfChild; 
     } 
    } 
    return null; 
}