Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent ListView from Resizing Window When Adding Items WPF/C#

Tags:

c#

listview

wpf

I have a ListView in WPF that is resizing my entire application window whenever I add items to it. I have the ListView size bound to the grid it is in, which is bound to the window size. So when the user resizes the window, the ListView grows. The problem is that when I add items to the ListView, it automatically stretches to try to fit the new content, which in turn stretches the size of the entire window.

Is there anyway to prevent this behavior from happening?

like image 508
Kirk Ouimet Avatar asked Jun 26 '10 22:06

Kirk Ouimet


3 Answers

Change SizeToContent of your window to Manual or Width (no Height should be there). This would prevent window itself from changing its height automatically according to content.

like image 87
tkola Avatar answered Nov 03 '22 01:11

tkola


You want to set the VerticalAlignment property to 'Stretch'. If necessary, in the parent control too, and so on, until you are in the Window control.

The caveat is that if one of the controls on the way up is a StackPanel, it will not stretch to fit, but ALWAYS expand to accommodate its content. So stay away from StackPanels, use Stretch, and you're set!

Remove your Bindings too, they are likely TwoWay: So the listview increasing its size is making your Window grow!

Hope that helps!

like image 40
Kieren Johnstone Avatar answered Nov 03 '22 01:11

Kieren Johnstone


You can use the following code.

First get the value of listview onload. Then store it in a variable, then do this code in the ColumnWidthChanging event property like this:

     e.cancel = true;
     e.NewWidth = // the declared variable in which you store the list view with value in the onload function of the form

 int a = 100;
    e.cancel =true;
    e.NewWidth = a;
like image 1
nelzkie Avatar answered Nov 03 '22 01:11

nelzkie