wpf的datagrid列选中后改变颜色

[size=medium]wpf的datagrid列选中后改变颜色[/size]


<UserControl.Resources>
<Style x:Key="CellStyle" TargetType="{x:Type DataGridCell}">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="Black"/>
<!--<Setter Property="BorderThickness" Value="0,0,0,0"/>-->
<Setter Property="BorderBrush" Value="Transparent"/>
</Trigger>
<!--<Trigger Property="DataGridRow.IsFocused" Value="True">
<Setter Property="Background" Value="Red" />
</Trigger>-->
</Style.Triggers>
</Style>
<Style x:Key="CellStyle2" TargetType="{x:Type DataGridCell}">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="Yellow" />
<Setter Property="Foreground" Value="Black"/>

</Trigger>
<Trigger Property="DataGridRow.IsFocused" Value="True">
<Setter Property="Background" Value="Red" />
</Trigger>
</Style.Triggers>
</Style>
</UserControl.Resources>

在Windows Presentation Foundation (WPF)中,要在DataGrid控件中实现选中改变底色的功能,你可以创建一个自定义的`DataGridCellStyle`,然后关联到DataGrid的`SelectedRowBackground`属性上。以下是一个简单的示例程序: ```xml <!-- XAML --> <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="450" Width="800"> <Window.Resources> <SolidColorBrush x:Key="SelectedBackgroundColor" Color="#FFBFBF"/> </Window.Resources> <DataGrid ItemsSource="{Binding YourDataSource}" SelectionChanged="DataGrid_SelectionChanged"> <DataGrid.RowStyle> <Style TargetType="DataGridRow"> <Setter Property="Background" Value="{StaticResource SelectedBackgroundColor}"/> </Style> </DataGrid.RowStyle> </DataGrid> </Window> ``` 在这个例子中,我们首先在窗口资源中定义了一个名为`SelectedBackgroundColor`的 SolidColorBrush,并设置了选择项背景颜色为浅粉色。接着,在DataGrid的`Resources`部分添加了这个样式,当DataGrid选中项发生变化时,`SelectionChanged`事件会被触发。 接下来是C#部分的`DataGrid_SelectionChanged`方法: ```csharp private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.AddedItems.Count > 0 && e.RemovedItems.Count == 0) { // 当有新的行被选中时,更新背景色 var selectedRow = ((DataGrid)sender).SelectedItem as FrameworkElement; if (selectedRow != null) { selectedRow.Background = new SolidColorBrush(Colors.LightBlue); } } } ``` 在这个方法里,我们检查是否有新增加的选中项,并将新选中的行背景色设置为浅蓝色。如果删除了某个选中的项目,背景色会自动恢复到原来的设定。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值