有一种风格HorizontallyCenteredCellStyle
:
<Style x:Key="HorizontallyCenteredCellStyle" TargetType="DataGridCell">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DataGridCell">
<Grid Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
风格LeftAlignedCellStyle
:
<Style x:Key="LeftAlignedCellStyle" TargetType="DataGridCell" BasedOn="{StaticResource HorizontallyCenteredCellStyle}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DataGridCell">
<Grid Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Left"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
DataGrid
还有从数据库加载数据的Xaml 标记:
<DataGrid x:Name="ObserveContactsPageDataGrid" Grid.Row="1" AutoGenerateColumns="False" IsReadOnly="True">
<DataGrid.ColumnHeaderStyle>
<Style TargetType="DataGridColumnHeader" BasedOn="{StaticResource HorizontallyCenteredHeaderStyle}"/>
</DataGrid.ColumnHeaderStyle>
<DataGrid.CellStyle>
<Style TargetType="DataGridCell" BasedOn="{StaticResource HorizontallyCenteredCellStyle}"/>
</DataGrid.CellStyle>
<DataGrid.Columns>
<DataGridTextColumn Header="№" Binding="{Binding ID}" Width="Auto"/>
<DataGridTextColumn Header="Номер телефона" Binding="{Binding PhoneNumber}" Width="Auto"/>
<DataGridTextColumn Header="Тип телефона" Binding="{Binding PhoneType}" Width="Auto"/>
<DataGridTextColumn Header="Имя" Binding="{Binding Name}" CellStyle="{StaticResource LeftAlignedCellStyle}" Width="100"/>
<DataGridTextColumn Header="Фамилия" Binding="{Binding Surname}" CellStyle="{StaticResource LeftAlignedCellStyle}" Width="100"/>
<DataGridTextColumn Header="Отчество" Binding="{Binding Patronymic}" Width="Auto"/>
<DataGridTextColumn Header="Пол" Binding="{Binding Sex}" Width="Auto"/>
</DataGrid.Columns>
</DataGrid>
但是,一旦取消“名字”和“姓氏”列单元格的左对齐,文本就会立即开始移动:
<!-- Стиль выравнивания влево убран -->
<DataGridTextColumn Header="Имя" Binding="{Binding Name}" Width="100"/>
<DataGridTextColumn Header="Фамилия" Binding="{Binding Surname}" Width="100"/>
尽管它应该与中心对齐,就像其他扬声器(成功地)发生的那样。
为什么这种情况只发生在这些扬声器上?这和什么有关系呢?
答:原来是插入数据库的数据有错误——需要检查其正确性。
更多详情:
由于某种原因,数据被插入到“名字”和“姓氏”字段中,单词后有一堆空格,字段旁边的省略号证明了这一点:
结论:需要通过调试来检查数据的正确性。对我有帮助的是手动创建条目,如下所示:
然后我简单地将这些数据添加到
List<T>
,将该列表与从数据库加载的数据列表合并,并将其添加到ObserveContactsPageDataGrid.ItemsSource
。结果如下:
有问题的条目 5 刚刚可见(姓氏 - Gorin)