DataGrid样式

it2024-09-27  15

1、自定义列(DataGridTemplateColumn)

<DataGridTemplateColumn Width="130"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Image Source="D:\资源\图片\VR.png" Width="20" Visibility="{Binding Path=url,Converter={StaticResource visibilityConvert}}"/> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn>

  中间用了一个转换器 visibilityConvert,因为我要实现有url字段时显示图片没有就不显示图片

      转换器:

public class UrlToVisibility : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null){ value = ""; }; string result = value.ToString(); if (result==null || result=="") { return Visibility.Hidden; } else { return Visibility.Visible; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }

  界面引用:<convert:UrlToVisibility x:Key="visibilityConvert"/> 即可

2、改变选中行的样式

  在网上找的别人的代码是这样的

<DataGrid.RowStyle> <Style TargetType="DataGridRow"> <Setter Property="Height" Value="40"></Setter> <Setter Property ="Background" Value ="#4C238BFF"/> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Background" Value="#FF6493CE"/> </Trigger> <Trigger Property="IsSelected" Value="True"> <Setter Property="Background" Value="#b58d20"/> <Setter Property="Foreground" Value="Yellow"/> </Trigger> </Style.Triggers> </Style> </DataGrid.RowStyle>

  可是并没有实现我想要的效果,后来才知道原来是被CellStyle挡住了RowStyle重新设置CellSyle即可

<DataGrid.CellStyle> <Style TargetType="DataGridCell"> <Setter Property="BorderThickness" Value="0"/> <Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="Background" Value="#FF6493CE"/> <Setter Property="Foreground" Value="Yellow"/> </Trigger> </Style.Triggers> </Style> </DataGrid.CellStyle>

3、添加复选框列(继续采用上面的自定义列实现):

<DataGridTemplateColumn Header=" " Width="50"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <CheckBox Background="Transparent" BorderBrush="AliceBlue" BorderThickness="1" Tag="{Binding}" VerticalAlignment="Center" HorizontalAlignment="Center" Checked="Cb_Checked" Unchecked="Cb_Checked" > <CheckBox.Template> <ControlTemplate TargetType="CheckBox"> <Border Width="16" Height="16" BorderBrush="Red" BorderThickness="1" Background="#22238BFF"> <Path Data="M 2,8 L6,12 12,2" Fill="Transparent" Opacity="0" Stroke="Yellow" StrokeThickness="2" VerticalAlignment="Center" HorizontalAlignment="Left" x:Name="selectpath"/> </Border> <ControlTemplate.Triggers> <Trigger Property="IsChecked" Value="True"> <Setter Property="Opacity" TargetName="selectpath" Value="1"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </CheckBox.Template> </CheckBox> </DataTemplate> </DataGridTemplateColumn.CellTemplate></DataGridTemplateColumn>

效果图如下:

 

转载于:https://www.cnblogs.com/zqyw/p/10912258.html

相关资源:修改样式后的Datagrid
最新回复(0)