开发者

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

开发者 https://www.devze.com 2023-01-05 01:09 出处:网络
I have a ListView in WPF that is resizing my entire application window whenever I add items to it. I have the ListV开发者_开发技巧iew size bound to the grid it is in, which is bound to the window size

I have a ListView in WPF that is resizing my entire application window whenever I add items to it. I have the ListV开发者_开发技巧iew 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?


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.


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!


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;


Have you tried setting the MaxWidth property?


You can set the MaxHeight property for your ListView in your xaml, no?


10 years later...

  1. Put the ListView inside a flexible control which resizes as you resize the window, for example, a Border. This way, when the Window resizes, the Border resizes, and when the Border resizes, the ListView resizes.

  2. Bind the MaxHeight property of the ListView to the ActualHeight property of the Border. This way, the ListView cannot resize the Border.

For details on how to achieve this, see this answer (to a practically duplicate question which is also about 10 years old): https://stackoverflow.com/a/68498797/773113

0

精彩评论

暂无评论...
验证码 换一张
取 消