1

我有一个包含许多 DataGridTemplateColumns 的 DataGrid。其中一个具有 Width="*",其余的具有 Width="Auto"。大多数只包含一个文本框。我想要每个元素的每一边都有一个边距,所以在分配给 TextBox 的样式中,我有 Margin="10,1"。我观察到的是 DataGrid 的初始宽度太宽了。如果手动使窗口变薄,DataGrid 也会变薄——但会保持超宽。如果窗口变大,DataGrid 将不会变宽,直到它的宽度正确,从那时起调整大小将正常工作。

如果我从样式中删除边距并将其显式放置在每列的 TextBox 中,那么一切都按预期工作,所以我的问题就解决了。但是我仍然想知道发生了什么,因为如果我想改变这些边距,那么改变一种风格会好得多。这是 DataGrid 中的一些奇怪的错误还是我理解不正确的东西?

DataGrid 嵌套在其他一些项目中,但由于修复非常简单,我认为 DataGrid 和样式是唯一重要的因素。

列看起来像这样;

<DataGridTemplateColumn x:Name="SKUColumn"
            Header="SKU" 
            Width="Auto">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBox x:Name="skuText"
                     Text="{Binding Path=SKU, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
                     Style="{StaticResource textBodyCell}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

和 textBodyCell 看起来像这样;

<Style x:Key="textBodyCell" TargetType="{x:Type TextBox}">
    <Setter Property="FontSize"
            Value="{StaticResource bodySize}" />
    <Setter Property="TextWrapping" Value="NoWrap"/>
    <Setter Property="AcceptsReturn" Value="False"/>
    <Setter Property="Margin" Value="10,1"/>
    <Setter Property="Template" Value="{DynamicResource DataGridCellTextBox}"/>

</Style>

DataGridCellTextBox 在哪里

<ControlTemplate x:Key="DataGridCellTextBox" TargetType="{x:Type TextBoxBase}">

    <ScrollViewer x:Name="PART_ContentHost" Foreground="{StaticResource DataGridUnSelectedRowForeground}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>

    <ControlTemplate.Triggers>
        <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridRow}}}" Value="True">
            <Setter Property="Foreground"  Value="{StaticResource DataGridSelectedRowForeground}" />
        </DataTrigger>
            <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridRow}}}" Value="False">
            <Setter Property="Foreground"  Value="{StaticResource DataGridUnSelectedRowForeground}" />
        </DataTrigger>          

        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>
4

0 回答 0