Save position and size of ColumnHeader automaticly
I you want to save automaticly position and size of Columnheader for a ListView you can use this AttachedProperty
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
public class ListViewHelper { #region API [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); private static void IniWrite(string path, string section, string key, string value) { WritePrivateProfileString(section, key, value, path); } private static string IniRead(string path, string section, string key) { StringBuilder temp = new StringBuilder(255); int i = GetPrivateProfileString(section, key, "", temp, 255, path); return temp.ToString(); } #endregion #region const & record private const string KEY_COL = "cols"; private const string KEY_SIZ = "sizes"; private record struct Parameter(bool UseIni, string Compagny, string Product, string FileIni, RegistryKey? RegistryKey); #endregion #region static parameter (UseIni dfefault = true // set in app.cs or before first InitializeComponent(); public static bool UseIni { get; set; } = true; #endregion #region SaveColumnPositionID public static string GetSaveColumnPositionID(DependencyObject obj) => (string)obj.GetValue(SaveColumnPositionIDProperty); public static void SetSaveColumnPositionID(DependencyObject obj, string value) => obj.SetValue(SaveColumnPositionIDProperty, value); public static readonly DependencyProperty SaveColumnPositionIDProperty = DependencyProperty.RegisterAttached("SaveColumnPositionID", typeof(string), typeof(ListViewHelper), new PropertyMetadata(null, (ss, ee) => { if (ss is ListView lv) { #region informations compagny & product var param = new Parameter(UseIni, "", "", "", null); var vi = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location); param.Compagny = vi.CompanyName ?? "[Common]"; param.Product = vi.ProductName; #endregion #region For IniFile if (UseIni) { // localisation %APPDATA%\[compagny]\[product].ini // [ID] // cols = 3 | 2 | 1 | 0 | // sizes = NaN | 64.4 | 208.17660377358487 | NaN | var dirIni = System.IO.Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), $"{param.Compagny}"); if (!System.IO.Directory.Exists(dirIni)) { System.IO.Directory.CreateDirectory(dirIni); } var fileNameIni = $"{param.Product}.ini"; param.FileIni = System.IO.Path.Combine(dirIni, fileNameIni); #if SHOW Debug.WriteLine($"Chemin = {param.FileIni}"); #endif } #endregion #region use registry else { // localisation Computer\HKEY_CURRENT_USER\SOFTWARE\{compagny]\[product]\[Id] // key cols // key sizes var rk = Registry.CurrentUser.CreateSubKey(@$"SOFTWARE\{param.Compagny}"); param.RegistryKey = rk.CreateSubKey($"{param.Product}"); } #endregion #region LayoutUpdated bool firstUpdated = true; lv.LayoutUpdated += delegate { if (firstUpdated) { firstUpdated = false; #region Get Column & create list if (FindChild<GridViewHeaderRowPresenter>(lv) is GridViewHeaderRowPresenter gvhrp) { #region set ColumID int i = 0; foreach (var c in gvhrp.Columns) { SetColumnID(c, i++); } #endregion string cols = "", sizes = ""; #region IniFile if (UseIni) { if (System.IO.File.Exists(param.FileIni)) { (cols, sizes) = ReadIni(param, (string)ee.NewValue); } } #endregion #region Use registry else { (cols, sizes) = ReadRegistry(param, (string)ee.NewValue); } #endregion SetColumnsValues(gvhrp.Columns, cols, sizes); }; lv.Loaded += delegate { // connecty for change var gvhrp = FindChild<GridViewHeaderRowPresenter>(lv); var pd = DependencyPropertyDescriptor.FromProperty(GridViewColumn.WidthProperty, typeof(GridViewColumn)); foreach (var c in gvhrp.Columns) { pd.AddValueChanged(c, delegate { UpdateDatas(param, (string)ee.NewValue, gvhrp.Columns); }); } // notification if change gvhrp.Columns.CollectionChanged += delegate { UpdateDatas(param, (string)ee.NewValue, gvhrp.Columns); }; }; #endregion #region - Local functions ----------------------------------------- void UpdateDatas(Parameter param, string id, GridViewColumnCollection collection) { if (param.UseIni) { WriteIni(param, id, collection); } else { WriteRegistry(param, id, collection); } } #region For Ini file (string col, string size) ReadIni(Parameter param, string id) { string cols = IniRead(param.FileIni, id, KEY_COL); string sizes = IniRead(param.FileIni, id, KEY_SIZ); #if SHOW Debug.WriteLine($"colonnes = {cols}"); Debug.WriteLine($"size = {sizes}"); #endif return (cols, sizes); } void WriteIni(Parameter param, string id, GridViewColumnCollection collection) { var (cols, sizes) = GetColumnsValues(collection); IniWrite(param.FileIni, id, KEY_COL, cols); IniWrite(param.FileIni, id, KEY_SIZ, sizes); } #endregion #region For registry (string col, string size) ReadRegistry(Parameter param, string id) { RegistryKey rk = param.RegistryKey.CreateSubKey(id); string cols = (string)rk.GetValue(KEY_COL); string sizes = (string)rk.GetValue(KEY_SIZ); #if SHOW Debug.WriteLine($"colonnes = {cols}"); Debug.WriteLine($"size = {sizes}"); #endif return (cols, sizes); } void WriteRegistry(Parameter param, string id, GridViewColumnCollection collection) { var (cols, sizes) = GetColumnsValues(collection); RegistryKey rk = param.RegistryKey.CreateSubKey(id); rk.SetValue(KEY_COL, cols); rk.SetValue(KEY_SIZ, sizes); } #endregion #region colum set and get (string col, string size) GetColumnsValues(GridViewColumnCollection collection) { string cols = "", sizes = ""; foreach (var c in collection) { cols += GetColumnID(c) + "|"; sizes += c.Width.ToString(CultureInfo.InvariantCulture) + "|"; } #if SHOW Debug.WriteLine($"colonnes = {cols}"); Debug.WriteLine($"size = {sizes}"); #endif return (cols, sizes); } void SetColumnsValues(GridViewColumnCollection collection, string cols, string sizes) { string[] colsSort = cols?.Split('|'); string[] sizesWidth = sizes?.Split('|'); if (colsSort != null && sizesWidth != null && collection.Count == colsSort.Length - 1 && colsSort.Length == sizesWidth.Length) { var colsList = new List<GridViewColumn>(); foreach (var item in collection) { colsList.Add(item); } gvhrp.Columns.Clear(); for (int index = 0; index < colsSort.Length - 1; index++) { try { int pos = int.Parse(colsSort[index]); gvhrp.Columns.Add(colsList[pos]); if (!sizesWidth[index].ToLower().Equals("nan")) { colsList[pos].Width = double.Parse(sizesWidth[index], CultureInfo.InvariantCulture); } } catch { } } } } #endregion #endregion } }; #endregion } })); #endregion #region ColumnID (private used only by SavecolumPositionID) private static int GetColumnID(DependencyObject obj) => (int)obj.GetValue(ColumnIDProperty); private static void SetColumnID(DependencyObject obj, int value) => obj.SetValue(ColumnIDProperty, value); private static readonly DependencyProperty ColumnIDProperty = DependencyProperty.RegisterAttached("ColumnID", typeof(int), typeof(ListViewHelper), new PropertyMetadata(0)); #endregion #region STATIC private static T FindChild<T>(DependencyObject parent, string childName = null) where T : DependencyObject { if (parent == null) return null; T foundChild = null; int childrenCount = VisualTreeHelper.GetChildrenCount(parent); for (int i = 0; i < childrenCount; i++) { var child = VisualTreeHelper.GetChild(parent, i); T childType = child as T; if (childType == null) { foundChild = FindChild<T>(child, childName); if (foundChild != null) break; } else if (!string.IsNullOrEmpty(childName)) { var frameworkElement = child as FrameworkElement; if (frameworkElement != null && frameworkElement.Name == childName) { foundChild = (T)child; break; } } else { foundChild = (T)child; break; } } return foundChild; } #endregion } |
and use like
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<ListView x:Name="lv" BorderThickness="1" ItemsSource="{Binding Missions}" Height="149" local:ListViewHelper.SaveColumnPositionID="first" VerticalAlignment="Top"> <ListView.View> <GridView> <GridViewColumn Header=" A " DisplayMemberBinding="{Binding Number}" /> <GridViewColumn Header=" B " DisplayMemberBinding="{Binding Status}" /> <GridViewColumn Header=" C " DisplayMemberBinding="{Binding Status}" /> <GridViewColumn Header=" D" DisplayMemberBinding="{Binding Status}"> </GridViewColumn> </GridView> </ListView.View> |
the SaveColumnPositionID is the uniq Id of ListView for saving
two possibilities
- first in ini file (by default)
%APPDATA%\[compagny]\[product].ini
// [ID]
// cols = 3|2|1|0|
// sizes = NaN|64.4|208.17660377358487|NaN|
- second in Registry
Computer\HKEY_CURRENT_USER\SOFTWARE\[compagny]\[product]\[Id]
// key cols = 3|2|1|0|
// key sizes = NaN|64.4|208.17660377358487|NaN|
for switch to registry you must insert this code
ListViewHelper.UseIni = false;
before all (in app for sample)
InitializeComponent();
this parameter is Global for all application
and you must have a different SaveColumnPositionID for each ListView
Categories: Non classé
Commentaires récents