我的視窗上有一個 Datagrid,在 XAML 中添加了 2 列,在后面的代碼中添加了 1 列。通過添加背景設定為 null 的 DataGridCell 樣式,我設法從前 2 列中洗掉了藍色。但是在后面的代碼中我無法讓它作業。
這是 Window.xaml
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:System="clr-namespace:System;assembly=mscorlib" x:Class="WpfApp1.MainWindow"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Background" Value="{x:Null}" />
<Setter Property="BorderBrush" Value="{x:Null}" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="{x:Null}" />
<Setter Property="BorderBrush" Value="{x:Null}" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<DataGrid x:Name="CandidatesEpisodesMatrix"
ColumnWidth="*"
AutoGenerateColumns="False" CanUserAddRows="False" HeadersVisibility="Column" SnapsToDevicePixels="True" SelectionUnit="Cell" RowDetailsVisibilityMode="Collapsed" >
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" />
<DataGridCheckBoxColumn/>
<!-- Other columns are added dynamically -->
</DataGrid.Columns>
<System:Object/>
<System:Object/>
</DataGrid>
</Grid>
</Window>
這是我背后的代碼:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
AddMatrixColumn();
}
private void AddMatrixColumn()
{
var factory = new FrameworkElementFactory(typeof(CheckBox));
var columnCellTemplate = new DataTemplate(typeof(CheckBox));
columnCellTemplate.VisualTree = factory;
var style = new Style();
style.Setters.Add(new Setter(HorizontalAlignmentProperty, HorizontalAlignment.Stretch));
style.Triggers.Add(new DataTrigger
{
Binding = new Binding("IsSelected"),
Value = true,
Setters =
{
new Setter(BackgroundProperty, Brushes.BlueViolet),
new Setter(BorderBrushProperty, Brushes.Aqua),
}
});
var headerStyle = new Style();
headerStyle.Setters.Add(new Setter(HorizontalAlignmentProperty, HorizontalAlignment.Center));
var column = new DataGridTemplateColumn();
column.Header = "episode.Name";
column.HeaderStyle = headerStyle;
column.CellTemplate = columnCellTemplate;
column.CellStyle = style;
CandidatesEpisodesMatrix.Columns.Add(column);
}
}
我曾希望通過在樣式中添加觸發器來更改背景顏色,但它不起作用。我究竟做錯了什么?
uj5u.com熱心網友回復:
找到了!我幾乎與觸發器在那里。不是 a ,而是應該使用DataTriggernormal 。Trigger這就是觸發器應該是什么:
style.Triggers.Add(new Trigger
{
Property = DataGridCell.IsSelectedProperty,
Value = true,
Setters =
{
new Setter(BackgroundProperty, Brushes.Transparent), // Or whatever color
new Setter(BorderBrushProperty, Brushes.Transparent),
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/448338.html
上一篇:在MVVM中處理事件
