Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static class GridEx
- {
- public static int GetRowCount(Grid obj) => (int)obj.GetValue(RowCountProperty);
- public static void SetRowCount(Grid obj, int value) => obj.SetValue(RowCountProperty, value);
- public static readonly DependencyProperty RowCountProperty =
- DependencyProperty.RegisterAttached("RowCount", typeof(int), typeof(GridEx), new PropertyMetadata(0, OnRowsChanged));
- public static string GetRowHeights(Grid obj) => (string)obj.GetValue(RowHeightsProperty);
- public static void SetRowHeights(Grid obj, string value) => obj.SetValue(RowHeightsProperty, value);
- public static readonly DependencyProperty RowHeightsProperty =
- DependencyProperty.RegisterAttached("RowHeights", typeof(string), typeof(GridEx), new PropertyMetadata("", OnRowsChanged));
- private static void OnRowsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
- {
- var grid = (Grid)d;
- var rowDefinitions = grid.RowDefinitions;
- var rowCount = GetRowCount(grid);
- var rowHeightsString = GetRowHeights(grid);
- var rowHeights = ParseRowHeightsString(rowHeightsString);
- var rowCountTotal = Math.Max(rowCount, rowHeights.Length);
- if (rowDefinitions.Count > rowCountTotal)
- rowDefinitions.RemoveRange(rowCount, rowDefinitions.Count - rowCountTotal);
- for (int i = 0; i < rowHeights.Length; ++i)
- {
- if (rowDefinitions.Count <= i)
- rowDefinitions.Add(new RowDefinition { Height = rowHeights[i] });
- if (rowDefinitions[i].Height != rowHeights[i])
- rowDefinitions[i].Height = rowHeights[i];
- }
- while (rowDefinitions.Count < rowCount)
- rowDefinitions.Add(new RowDefinition());
- }
- private static GridLength[] ParseRowHeightsString(string rowHeightsString)
- {
- var parts = rowHeightsString.ToUpper()
- .Split(" ,".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
- var gridLengths = new GridLength[parts.Length];
- for (int i = 0; i < parts.Length; ++i)
- {
- if (parts[i] == "AUTO") continue;
- int endSymbolIndex = parts[i].Length - 1;
- if (parts[i][endSymbolIndex] == '*')
- {
- double value = 1;
- if (parts[i].Length > 1
- && !double.TryParse(parts[i].Substring(0, endSymbolIndex), out value))
- throw new ArgumentException("Illegal argument RowHeights");
- gridLengths[i] = new GridLength(value, GridUnitType.Star);
- continue;
- }
- if (!double.TryParse(parts[i], out var pixels))
- throw new ArgumentException("Illegal argument RowHeights");
- gridLengths[i] = new GridLength(pixels);
- }
- return gridLengths;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement