- xaml代码
xml
<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}">
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="FontSize" Value="16"/>
<Setter Property="Padding" Value="0 10"/>
</Style>
<!--设置行样式-->
<Style x:Key="CenteredTextBlockStyle" TargetType="{x:Type TextBlock}">
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="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}">
<Setter Property="CornerRadius" Value="5"/>
</Style>
</Button.Resources>
</Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
2.cs代码
csharp
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 }
// 添加更多产品...
};
}