Prevent wpf listview header double click autosizes column

I have a list in which I template column headings, and list items are also templates. However, I have different templates for some lines in the form of a grid. When the user double-clicks on the column heading of the list, where you can drag the column width, the column heading will automatically resize, i.e. increase its size. This causes a problem for me, because my column header width is no longer in sync with the column width in my row templates.

Is there a quick and easy way to prevent this double-click behavior in a column header?

+1
source share
2 answers

Yes, configure the double-click handler on the ListView itself. Then in the handler, use the following code:

 private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if (TryFindParent<GridViewColumnHeader>(e.OriginalSource as DependencyObject) != null) e.Handled = true; } 

Where TryFindParent is defined as:

 public static T TryFindParent<T>(DependencyObject current) where T : class { DependencyObject parent = VisualTreeHelper.GetParent(current); if (parent == null) return null; if (parent is T) return parent as T; else return TryFindParent<T>(parent); } 
+2
source

I found a working solution after digging in the source code of the GridViewColumnHeader. My XAML for ListView with columns:

  <ListView.View> <GridView AllowsColumnReorder="False" x:Name="ListGridView"> <GridView.Columns> <GridViewColumn x:Name="ExpandHeader" Width="40"> <GridViewColumn.Header> <GridViewColumnHeader IsHitTestVisible="False" /> </GridViewColumn.Header> </GridViewColumn> 

And you need to put such code in the View Loaded event (when creating the columns):

  private void ViewOnLoaded(object sender, RoutedEventArgs e) { var fields = typeof(GridViewColumnHeader).GetFields(BindingFlags.NonPublic | BindingFlags.Instance); var thumbFieldInfo = fields.FirstOrDefault(fi => fi.FieldType == typeof(Thumb)); var methods = typeof(GridViewColumnHeader).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance); var eventHandlerMethodInfo = methods.FirstOrDefault(mi => mi.Name == "OnGripperDoubleClicked"); if (thumbFieldInfo != null && eventHandlerMethodInfo != null) { foreach (var column in ListGridView.Columns) { var header = column.Header as GridViewColumnHeader; if (header != null) { var headerGripper = thumbFieldInfo.GetValue(header) as Thumb; if (headerGripper != null) { var handler = Delegate.CreateDelegate(typeof(MouseButtonEventHandler), header, eventHandlerMethodInfo); headerGripper.RemoveHandler(Control.MouseDoubleClickEvent, handler); } } } } } 
0
source

Source: https://habr.com/ru/post/1385174/


All Articles