使用WPF 制作漂亮的datagrid样式
时间: 2023-09-17 18:14:58 浏览: 80
WPF 中的 DataGrid 控件是一个强大的工具,可用于在应用程序中显示和编辑数据集。要创建漂亮的 DataGrid 样式,可以使用以下步骤:
1. 创建一个新的 WPF 应用程序项目。
2. 在项目中添加一个 DataGrid 控件。
3. 在 DataGrid 控件中设置 AutoGenerateColumns 属性为 False。这将使您能够手动指定列。
4. 添加所需的列。可以添加 TextBlock、ComboBox、CheckBox 等控件作为列的元素。
5. 为 DataGrid 添加样式。可以使用样式来更改 DataGrid 中每个单元格的外观,例如背景色、前景色、字体大小等。
6. 为 DataGrid 添加模板列。模板列允许您在 DataGrid 中嵌入自定义控件。
以下是一个简单的示例,演示如何创建具有漂亮样式的 DataGrid:
```xml
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="450" Width="800">
<Grid>
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding}">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Photo">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding Photo}" Width="50" Height="50"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="*"/>
<DataGridTextColumn Header="Age" Binding="{Binding Age}" Width="*"/>
<DataGridTemplateColumn Header="Gender">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding GenderOptions}" SelectedItem="{Binding Gender}" Width="100"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="IsMarried">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsMarried}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="Background" Value="#EEE"/>
<Setter Property="Foreground" Value="#444"/>
<Setter Property="FontSize" Value="16"/>
</Style>
</DataGrid.RowStyle>
</DataGrid>
</Grid>
</Window>
```
在这个示例中,我们添加了四列。第一列是一个模板列,显示每个人的照片。第二列是一个文本列,显示每个人的姓名。第三列也是一个文本列,显示每个人的年龄。第四列是一个模板列,允许用户选择每个人的性别。第五列是一个模板列,允许用户选择每个人是否已婚。
最后,我们为 DataGrid 添加了一个样式。这个样式定义了 DataGrid 中每个行的背景色、前景色和字体大小。