2014-01-08 101 views
0

我怎样才能得到一个在xaml样式模板中使用的DataGrid控件在代码中使用它?如何在用户控制代码中获取模板中使用的控件?

<UserControl> 
<UserControl.Resources> 
    <Style x:Key="MyComboBoxStyle" TargetType="{x:Type ComboBox}"> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="{x:Type ComboBox}"> 
        <Grid x:Name="MainGrid" SnapsToDevicePixels="true"> 
         <Grid.ColumnDefinitions> 
          <ColumnDefinition Width="*" /> 
          <ColumnDefinition Width="0" MinWidth="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}" /> 
         </Grid.ColumnDefinitions> 
         <Popup x:Name="PART_Popup" 
           Grid.ColumnSpan="2"> 
          <Microsoft_Windows_Themes:SystemDropShadowChrome x:Name="Shdw"> 

           <Border x:Name="DropDownBorder"> 

            <DataGrid x:Name="PART_PopupDataGrid" /> 

           </Border> 
          </Microsoft_Windows_Themes:SystemDropShadowChrome> 
         </Popup> 
         <ToggleButton Grid.ColumnSpan="2" 
             Background="{TemplateBinding Background}" 
             BorderBrush="{TemplateBinding BorderBrush}" 
             IsChecked="{Binding Path=IsDropDownOpen, 
                  Mode=TwoWay, 
                  RelativeSource={RelativeSource TemplatedParent}}" 
             Style="{StaticResource ComboBoxReadonlyToggleButton}" /> 
         <ContentPresenter Margin="{TemplateBinding Padding}" 
              HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
              VerticalAlignment="{TemplateBinding VerticalContentAlignment}" 
              Content="{TemplateBinding SelectionBoxItem}" 
              ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}" 
              ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}" 
              IsHitTestVisible="false" 
              SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" /> 
        </Grid> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 
</UserControl.Resources> 

    <Grid> 
     <ComboBox Name="ComboGrid" Style="{DynamicResource DataGridComboBoxStyle}" /> 
    </Grid> 
</UserControl> 

还有就是我如何试图让用户控制DataGrid控件,但没有成功:

var v1 = this.FindName("PART_PopupDataGrid"); 
var v2 = this.Template.FindName("PART_PopupDataGrid", this); 
var v3 = ComboGrid.FindName("PART_PopupDataGrid"); 

我怎么能得到这个代码的控制?

回答

2

这是一个非常普遍的要求。事实上,这是很常见的,微软甚至在MSDN上的网页专门为此:

How to: Find ControlTemplate-Generated Elements

基本上,如果你有该ControlTemplate应用于到ComboBox参考(我们称之为ComboBox),那么你应该可以这样做:

DataGrid dataGrid = 
    ComboBox.Template.FindName("PART_PopupDataGrid", ComboBox) as DataGrid; 
+0

谢谢你解决了我的问题! – Lukas

+0

MSDN链接不再可用。新链接:https://msdn.microsoft.com/de-de/library/bb613586%28v=vs.85%29.aspx – ecreif

+0

谢谢@ecreif,但是您的链接适用于MSDN上的非英文页面。我发现了另一个链接来替换破损的链接。 – Sheridan

相关问题