2012-04-28 89 views
5

我需要創建一個通用的DataGridTemplateColumn,以便我可以在具有不同對象和屬性的應用程序中使用它。在WPF中創建公共DataGridTemplateColumn

這裏是一些示例代碼,我在我的項目中使用

<DataGridTemplateColumn Width="100*"> 
    <DataGridTemplateColumn.CellTemplate> 
     <DataTemplate> 
      <TextBlock Text="{Binding Path=Age}"/> 
     </DataTemplate> 
    </DataGridTemplateColumn.CellTemplate> 
    <DataGridTemplateColumn.CellEditingTemplate> 
     <DataTemplate> 
      <TextBox Text="{Binding Path=Age}"/> 
     </DataTemplate> 
    </DataGridTemplateColumn.CellEditingTemplate> 
</DataGridTemplateColumn> 

我需要的代碼的通用版本,這樣我可以把DataTemplateapp.xaml和我的代碼

+0

的[我可以定義的DataGrid的CellTemplate作爲一個資源可能的複製,以便它可以被重用在多列?](http://stackoverflow.com/questions/8354650/can-i-define-celltemplate-of-datagrid-as-a-resource-so-that-it-can-be-reused-in) – Athafoud 2016-10-21 09:00:51

回答

6

你引用它不能直接模板DataGridTemplateColumn。但幸運的是,您可以使用單元的全局模板。看看例子:

的App.xaml

<Application.Resources> 

    <DataTemplate x:Key="CellEdintingTemplate"> 
     <TextBox Text="{Binding Path=Age}" /> 
    </DataTemplate> 
    <DataTemplate x:Key="CellTemplate"> 
     <TextBlock Text="{Binding Path=Age}" /> 
    </DataTemplate> 

</Application.Resources> 

使用

<DataGrid> 
     <DataGrid.Columns> 
      <DataGridTemplateColumn 
       CellEditingTemplate="{StaticResource CellEdintingTemplate}" 
       CellTemplate="{StaticResource CellTemplate}" /> 
     </DataGrid.Columns> 
    </DataGrid>