How do I make XAML DataGridColumns fill the entire

2019-01-17 05:28发布

I am using DataGrids in XAML (not Silverlight) with resizable columns, the DataGrid will expand if the user resizes the screen.

Currently if the widths of all the DataGrid columns are less than the width of the DataGrid I get an extra "column" appearing which is unclickable and serves no purpose.

Does anyone know how to make one column always resize to fill all the remaining space?

9条回答
Lonely孤独者°
2楼-- · 2019-01-17 05:42

I added a HorizontalAlignment="Center" (The default is "Strech") and it solved my problem because it made the datagrid only as wide as needed. (Removed the datagrid's Width setting if you have one.)

enter image description here

查看更多
叛逆
3楼-- · 2019-01-17 05:53

If you use Width="*" the column will fill to expand the available space.

If you want all columns to divide the grid equally apply this to all columns. If you just want one to fill the remaining space just apply it to that column with the rest being "Auto" or a specific width.

You can also use Width="0.25*" (for example) if you want the column to take up 1/4 of the available width.

查看更多
Emotional °昔
4楼-- · 2019-01-17 05:53

For those looking for a C# workaround:

If you need for some reason to have the "AutoGeneratedColumns" enabled, one thing you can do is to specify all the columns's width except the ones you want to be auto resized (it will not take the remaining space, but it will resize to the cell's content).

Example (dgShopppingCart is my DataGrid):

dgShoppingCart.Columns[0].Visibility = Visibility.Hidden; 
dgShoppingCart.Columns[1].Header = "Qty";
dgShoppingCart.Columns[1].Width = 100;
dgShoppingCart.Columns[2].Header = "Product Name"; /*This will be resized to cell content*/
dgShoppingCart.Columns[3].Header = "Price";
dgShoppingCart.Columns[3].Width = 100;
dgShoppingCart.Columns[4].Visibility = Visibility.Hidden; 

For me it works as a workaround because I needed to have the DataGrid resized when the user maximize the Window.

查看更多
虎瘦雄心在
5楼-- · 2019-01-17 05:55

Set the columns Width property to be a proportional width such as *

查看更多
劫难
6楼-- · 2019-01-17 05:55

As noted, the ColumnWidth="*" worked perfectly well for a DataGrid in XAML.

I used it in this context:

    <DataGrid ItemsSource="{Binding AllFolders, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ColumnWidth="*"/>
查看更多
劫难
7楼-- · 2019-01-17 05:58

This will not expand the last column of the xaml grid to take the remaining space if AutoGeneratedColumns="True".

查看更多
登录 后发表回答