WPF学习笔记(4):获取DataGridTemplateColumn模板定义的内容控件(转)

在之前的DataGrid的DataGridTemplateColumn列中,自定义了一个TextBox控件,但是在C#代码中提示找不到这个控件,导致无法对该控件进行操作。在网上搜索后,发现一些处理方法比较繁琐,下面这个方法最简便。

xaml格式描述:

复制代码
 1 <DataGrid Name="dataGrid" Grid.Row="1" ItemsSource="{Binding}"  >
 2        <DataGrid.Columns>
 3             <DataGridTemplateColumn Header="描述">
 4                     <DataGridTemplateColumn.CellTemplate>
 5                         <DataTemplate>
 6                             <Expander x:Name="expander" Header="{Binding Describe}">
 7                                 <TextBlock Text="{Binding Path=Exception}" TextWrapping="Wrap" MinHeight="30"  MinWidth="250" />
 8                             </Expander>
 9                         </DataTemplate>
10                     </DataGridTemplateColumn.CellTemplate>
11               </DataGridTemplateColumn>
12        </DataGrid.Columns>
13 </DataGrid>
复制代码
 

现在要获取expander控件,代码如下:

复制代码
1 int index = dataGrid.CurrentCell.Column.DisplayIndex;
2 DataGridTemplateColumn templeColumn = dataGrid.Columns[index] as DataGridTemplateColumn;
3 
4 if(templeColumn == null) return;
5 
6 object item = dataGrid.CurrentCell.Item;
7 FrameworkElement element = templeColumn.GetCellContent(item);
8 Expander expander= templeColumn.CellTemplate.FindName("expander", element);
复制代码

猜你喜欢

转载自www.cnblogs.com/LiZhongZhongY/p/10879460.html