后面的代码明确设置它。
我是WPF的新手,我不知道如何为数据杂志的列使用两个不同的控制模板(该模板将始终具有2列)。这是datagrid的XAML:
<DataGrid x:Name="HomeSoftwareGrid"
CanUserAddRows="false"
ItemsSource="{Binding CollectedSoftwares}"
AutoGenerateColumns="True"
FontSize="15"
ColumnWidth="*"
IsReadOnly="True"
AutoGeneratingColumn="OnAutoGeneratingColumn"
CellEditEnding="OnCellEditEnding"
HorizontalAlignment="Center"
MaxWidth="600">
</DataGrid>
我正在使用属性AutogeneratingColumn删除特定列并编辑列的标题
private void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
PropertyDescriptor propertyDescriptor = (PropertyDescriptor)e.PropertyDescriptor;
e.Column.Header = propertyDescriptor.DisplayName;
if (propertyDescriptor.DisplayName == "Resources")
{
e.Cancel = true;
}
else if (propertyDescriptor.DisplayName == "SoftwareStatus")
{
e.Column.Header = "Software Status";
}
else if (propertyDescriptor.DisplayName == "SoftwareName")
{
e.Column.Header = "Software Name";
}
}
这些是我要使用的内容模板,第一列的第一列,第二列明显是:d:
<!-- first column style -->
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<ContentPresenter Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Center" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- second column style -->
<Style x:Key="SoftwareStatusDataGridColumn" TargetType="{x:Type DataGridCell}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Grid HorizontalAlignment="Center">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Rectangle x:Name="ImgPartially" Grid.Column="0" Width="20" Height="20" Fill="Yellow">
<Rectangle.OpacityMask>
<VisualBrush Stretch="Uniform" Visual="{StaticResource appbar_warning}" />
</Rectangle.OpacityMask>
</Rectangle>
<ContentPresenter Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Center" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
我该如何实现?
事件的 sender
是datagrid,并且datagrid可以在其视觉树中找到单元格样式。然后,您可以单独分配该样式:
else if (propertyDescriptor.DisplayName == "SoftwareName")
{
e.Column.Header = "Software Name";
e.Column.CellStyle = (sender as FrameworkElement).FindResource("SoftwareStatusDataGridColumn") as Style;
}
<Style TargetType="{x:Type DataGridCell}">
此样式使用类型作为键,默认情况下将其分配给DataGridCells,无需从