<Window x:Class="YourNamespace.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Products}">
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridColumnHeader}">
"HorizontalContentAlignment" Value="Center"/>
"VerticalAlignment" Value="Center"/>
"FontSize" Value="16"/>
"Padding" Value="0 10"/>
Style>
<Style x:Key="CenteredTextBlockStyle" TargetType="{x:Type TextBlock}">
"VerticalAlignment" Value="Center"/>
"HorizontalAlignment" Value="Center"/>
"FontSize" Value="16"/>
Style>
DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="Id" Binding="{Binding Id}" />
<DataGridTemplateColumn Header="Name" Width="2*">
<DataGridTemplateColumn.CellTemplate >
<DataTemplate>
<ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto">
<TextBlock Text="{Binding Name}" TextWrapping="Wrap" Style="{StaticResource CenteredTextBlockStyle}"/>
ScrollViewer>
DataTemplate>
DataGridTemplateColumn.CellTemplate>
DataGridTemplateColumn>
<DataGridTextColumn Header="Price" Binding="{Binding Price}" />
<DataGridTemplateColumn Header="操作" Width="100">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button Content="编辑" Cursor="Hand" Click="editButton_Dianji" >
<Button.Resources>
<Style TargetType="{x:Type Border}">
"CornerRadius" Value="5"/>
Style>
Button.Resources>
Button>
StackPanel>
DataTemplate>
DataGridTemplateColumn.CellTemplate>
DataGridTemplateColumn>
DataGrid.Columns>
DataGrid>
Grid>
Window>
2.cs代码
public ObservableCollection<Product> Products { get; set; }
public MainWindow()
{
InitializeComponent();
this.DataContext = this; // 设置数据上下文为当前窗口实例
// 初始化产品集合
Products = new ObservableCollection<Product>
{
new Product { Id = 1, Name = "Product 1", Price = 10.99M },
new Product { Id = 2, Name = "Product 2", Price = 20.99M }
// 添加更多产品...
};
}