I have a DataGrid
with ColumnWidth="*"
in a ScrollViewer
with HorizontalScrollBarVisibility="Auto"
. Unfortunately this combination doesn't seem to work well. While the DataGrid
spans properly over the full window width the columns are super small ( MinWidth
). If I change HorizontalScrollBarVisibility
to Disabled
it works but I lose the desired ScrollViewer
behavior.
Minimal Working Example:
<Window x:Class="WPF_Sandbox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WPF_Sandbox"
Title="MainWindow"
x:Name="ThisControl">
<ScrollViewer HorizontalScrollBarVisibility="Auto">
<DataGrid AutoGenerateColumns="False" ColumnWidth="*">
<DataGrid.Columns>
<DataGridTextColumn Header="Column 1" />
<DataGridTextColumn Header="Column 2" />
<DataGridTextColumn Header="Column 3" />
<DataGridTextColumn Header="Column 4" />
</DataGrid.Columns>
</DataGrid>
</ScrollViewer>
</Window>
Why is this happening and how can I work around it?
The problem you see is because as the Datagrid is inside a ScrollViewer, it has virtually infinite space to expand,so it can't calculate widths. For this to work you can bind the DataGrid Width to the ScrollViewer ViewportWidth, as this:
<DataGrid AutoGenerateColumns="False" ColumnWidth="*"
Width="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ScrollViewer}}, Path=ViewportWidth}">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.