Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the last column in WPF datagrid take all the left space, always?

Tags:

wpf

datagrid

Standard WPF 4 Datagrid.

Let' say I have datagrid 200 pixels wide, and 2 columns. I would like the columns take always entire space, meaning if the user resizes the first column to 50 pixels, the last one would be 150.

Initially I set width 100 pixels for the 1st column, and * for the last one (in XAML).

I thought the problem is with removing the virtual, 3rd column, as explained here:

http://wpf.codeplex.com/Thread/View.aspx?ThreadId=58939

but there is no difference really -- still, when resizing the columns, I get some extra space on right -- with virtual column, it is a virtual column (white color by default), without it, it is empty space (gray by default).

QUESTION: how to enforce the constraint, that no matter how the user resizes the columns,

sum(columns width)==datagrid width 

?

Edits

Yes, I use WPF 4.

WORKAROUND

I marked one of the answers as solution, but actually it is not a solution due to WPF design. It is simply what WPF can do at best, and it is not very good -- first of all the option CanUserResize for column means really IsResizeable and this option when turned on contradicts Width set to *. So without some really smart trick you end up with:

  • datagrid which last column in superficially resizable but in fact it is not, and little space on right is shown (i.e. the virtual column is not resizable) -- for last column: CanUserResize=true, Width=*

  • datagrid which last column cannot be resized by user and it is shown accordingly, initially no space on right is shown, but it can be shown when user resizes any element of datagrid -- for last column: CanUserResize=false, Width=*

So far I can see two problems with WPF datagrid:

  • misleading naming
  • contradiction of features

I am still all ears to how really solve this issue.

like image 379
greenoldman Avatar asked Dec 08 '10 16:12

greenoldman


1 Answers

Set the width for the data grid to "Auto". You're allowing the columns to resize correctly within the grid itself, but you've hard-wired the width to 200.

UPDATE: Base on @micas's comment, I may have misread. If that's the case, try using 100 for the left column's width and 100* for the right column (note the asterisk). This will default the width for the right column to 100 but allow it to resize to fill the grid.

like image 143
Babak Naffas Avatar answered Sep 21 '22 01:09

Babak Naffas