我有中的列由ObservableCollection
設置,它是我創建的簡單數據對象的類型。第一列的寬度設置爲「自動」,第二列的寬度設置爲「1 *」。WPF Datagrid列寬問題
我目前在回答here中使用該方法來自動更新我的列的寬度,當ItemsSource
更改時,該列的寬度設置爲「自動」。這似乎工作的大部分時間:
這看起來不錯,和所有工作的時間
雖然,當ItemsSource
有點大(可以說約30-35條記錄)時, 「自動」 寬度(第一)列將收縮向下僅當DataGrid
(包括滾動條)是點擊:
這將是適當的調整,如果沒有被點擊它
我的XAML看起來像這樣:
<my:DataGrid CanUserSortColumns="false" CanUserResizeRows="false" CanUserResizeColumns="false" CanUserReorderColumns="false" CanUserDeleteRows="false" CanUserAddRows="false" AutoGenerateColumns ="False" SelectionMode="Single" SelectionUnit="Cell" Height="113" HorizontalAlignment="Left" Margin="11,22,0,0" Name="dataGrid" VerticalAlignment="Top" Width="226" Background="#FFE2E2E2" AlternatingRowBackground="#FFA4CFF2" BorderBrush="#FF7C7C7C" HorizontalGridLinesBrush="White" PreviewKeyDown="dataGrid_PreviewKeyDown" CellEditEnding="dataGrid_CellEditEnding" BeginningEdit="dataGrid_BeginningEdit" PreparingCellForEdit="dataGrid_PreparingCellForEdit" SelectedCellsChanged="dataGrid_SelectedCellsChanged" Loaded="dataGrid_Loaded" TargetUpdated="dataGrid_TargetUpdated">
<my:DataGrid.Columns>
<my:DataGridTextColumn Binding="{Binding Path=Name, NotifyOnTargetUpdated=True}" Width="Auto">
<my:DataGridTextColumn.CellStyle>
<Style TargetType="{x:Type my:DataGridCell}">
<Setter Property="KeyboardNavigation.IsTabStop" Value="False"></Setter>
<Setter Property="IsHitTestVisible" Value="False"></Setter>
<Setter Property="Focusable" Value="False"></Setter>
<Setter Property="Background" Value="WhiteSmoke"></Setter>
<Setter Property="BorderBrush" Value="LightGray"></Setter>
</Style>
</my:DataGridTextColumn.CellStyle>
</my:DataGridTextColumn>
<my:DataGridTextColumn Binding="{Binding Path=Value}" Width="1*"></my:DataGridTextColumn>
</my:DataGrid.Columns>
</my:DataGrid>
的代碼,以確保該列的更新:
private void dataGrid_TargetUpdated(object sender, DataTransferEventArgs e)
{
dataGrid.Columns[0].Width = 0;
dataGrid.UpdateLayout();
dataGrid.Columns[0].Width = new DataGridLength(0, DataGridLengthUnitType.Auto);
dataGrid.UpdateLayout();
}
是有沒有什麼理由可能會發生,只有當名單更長這樣?