כיצד להגדיר GridColumns (עמודות) ו-GridRows (שורות) בקלות ב-wpf בהשראת Avalonia
-
תמיד תופס הרבה מקום וזמן להגדיר שורות ועמודות בתוך פקד Grid ב-wpf
ראיתי מה הם עשו ב-Avalonia ותפסתי רעיון לעשות לעצמי Class שיעשה אותו הדבר.ברגיל צריך לעשות כך:
<Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="2*"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <\Grid>
עם ה-class שיצרתי אפשר לעשות כך:
<Grid local:GridSetup.Columns="Auto,*,2*" local:GridSetup.Rows="Auto,*,Auto">
מצו"ב סקיצה אשמח לקבל משוב
namespace RegexInWord.UI.Wpf { using System; using System.Windows.Controls; using System.Windows; public class GridSetup { private static GridLengthConverter _gridLengthConverter = new GridLengthConverter(); public static readonly DependencyProperty ColumnsProperty = DependencyProperty.RegisterAttached( "Columns", typeof(string), typeof(GridSetup), new PropertyMetadata(null, OnColumnsChanged)); public static void SetColumns(DependencyObject element, string value) => element.SetValue(ColumnsProperty, value); public static string GetColumns(DependencyObject element) => (string)element.GetValue(ColumnsProperty); private static void OnColumnsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is Grid grid && e.NewValue is string definition) { grid.ColumnDefinitions.Clear(); foreach (var item in definition.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { grid.ColumnDefinitions.Add(new ColumnDefinition { Width = ParseGridLength(item.Trim()) }); } } } public static readonly DependencyProperty RowsProperty = DependencyProperty.RegisterAttached( "Rows", typeof(string), typeof(GridSetup), new PropertyMetadata(null, OnRowsChanged)); public static void SetRows(DependencyObject element, string value) => element.SetValue(RowsProperty, value); public static string GetRows(DependencyObject element) => (string)element.GetValue(RowsProperty); private static void OnRowsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is Grid grid && e.NewValue is string definition) { grid.RowDefinitions.Clear(); foreach (var item in definition.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { grid.RowDefinitions.Add(new RowDefinition { Height = ParseGridLength(item.Trim()) }); } } } private static GridLength ParseGridLength(string value) { return (GridLength)_gridLengthConverter.ConvertFromString(value); } } }
-
אתה יכול להשתמש עם
GridLengthConverter
private static GridLengthConverter _gridLengthConverter = new GridLengthConverter(); private static GridLength ParseGridLength(string value) { return _gridLengthConverter.ConvertFromString(value); }
עוד משהו, מקובל להפריד עם עם רווח ולא רק פסיק.
ואגב אני חושב שזה הגיע מ - WinUI עוד לפני Avalonia