Paradox Game Engine  v1.0.0 beta06
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Events Macros Pages
GridViewAutoSizeBehavior.cs
Go to the documentation of this file.
1 // Copyright (c) 2014 Silicon Studio Corp. (http://siliconstudio.co.jp)
2 // This file is distributed under GPL v3. See LICENSE.md for details.
3 using System;
4 using System.Collections.Generic;
5 using System.Collections.Specialized;
6 using System.ComponentModel;
7 using System.Linq;
8 using System.Text;
9 using System.Threading.Tasks;
10 using System.Windows;
11 using System.Windows.Controls;
12 
13 namespace SiliconStudio.Presentation.Behaviors
14 {
15  public class GridViewAutoSizeBehavior : DeferredBehaviorBase<ListView>
16  {
17  /// <summary>
18  /// Gets or sets whether the columns are initialized with auto sizing or not.
19  /// Note: This parameter is used at initialization time only.
20  /// </summary>
21  public bool IsAutoSizedByDefault { get; set; }
22 
23  protected override void OnAttachedOverride()
24  {
25  var observableCollection = AssociatedObject.Items.SourceCollection as INotifyCollectionChanged;
26  if (observableCollection != null)
27  observableCollection.CollectionChanged += SourceCollectionChanged;
28 
29  var gridView = AssociatedObject.View as GridView;
30  if (gridView != null)
31  {
32  foreach (var column in gridView.Columns)
33  column.Width = IsAutoSizedByDefault ? double.NaN : column.ActualWidth;
34  }
35  }
36 
37  protected override void OnDetachingOverride()
38  {
39  var observableCollection = AssociatedObject.Items.SourceCollection as INotifyCollectionChanged;
40  if (observableCollection != null)
41  observableCollection.CollectionChanged -= SourceCollectionChanged;
42  }
43 
44  private void SourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
45  {
46  var gridView = AssociatedObject.View as GridView;
47  if (gridView != null)
48  UpdateAllColumns(gridView);
49  }
50 
51  private void UpdateAllColumns(GridView gridView)
52  {
53  foreach (var column in gridView.Columns)
54  UpdateColumn(column);
55  }
56 
57  private void UpdateColumn(GridViewColumn column)
58  {
59  // auto sizing
60  if (double.IsNaN(column.Width))
61  {
62  // reset size with actual size
63  column.Width = column.ActualWidth;
64  // set it back to auto sizing
65  column.Width = double.NaN;
66  }
67  }
68  }
69 }