我想为每个wpf datagrid列添加一个按钮。我的列是自动生成的,因此我没有xaml中列的定义。我怎么能用列的模板做到这一点,所以我有我的列标题,右边是一个按钮。
编辑:
<DataGrid ItemsSource="{Binding User.myDataTable}" AutoGenerateColumns="True">
<DataGrid.ColumnHeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Here I want my ColumnName" />
<Button Content="Button"/>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGrid.ColumnHeaderStyle>
</DataGrid>
User.myDataTable填写在模型中,并且工作正常。
答案 0 :(得分:0)
您可以使用样式:
<DataGrid>
<DataGrid.ColumnHeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding ColumnName}" />
<Button Content="Button" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid>
答案 1 :(得分:0)
use the below code:-
DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();
FrameworkElementFactory HeaderStackpanel = new FrameworkElementFactory(typeof(StackPanel));
FrameworkElementFactory btn = new FrameworkElementFactory(typeof(Button));
// Set the property for Button
btn.SetValue(Button.MarginProperty, new Thickness(-50, 0, 0, 0));
btn.AddHandler(Button.ClickEvent, new RoutedEventHandler(BtnClick));
// Set the Text Value to the buttons
btn.SetValue(Button.ContentProperty, strEdit);
// Append the Edit Button
HeaderStackpanel.AppendChild(btn);
DataTemplate headerTemplate = new DataTemplate();
headerTemplate.VisualTree = HeaderStackpanel;
templateColumn.HeaderTemplate = headerTemplate;