我厌倦了写出我RowDefinitions
的ColumnDefinitions
网格,所以创建了一些自定义的 DependencyProperties,让您在网格定义中指定行/列的数量。
可以在此处找到依赖属性的代码,并按如下方式使用:
<Grid local:GridHelpers.RowCount="{Binding RowCount}"
local:GridHelpers.ColumnCount="{Binding ColumnCount}" />
如果它为您提供有关绑定的错误typeof(Grid)
,则将 DependencyProperty 定义中的 更改为typeof(GridHelpers)
. 我的第一个版本的助手类不允许绑定,我不记得我发布了哪个。
编辑
这是我正在使用的有效代码,包括在SomeInt
更改时正确更新 UI。SomeInt
单击按钮时,我正在测试在 2 和 3 之间切换
XAML
<Grid ShowGridLines="True"
local:GridProperties.ColumnCount="{Binding SomeInt}"
local:GridProperties.RowCount="{Binding SomeInt}">
<TextBox Text="Test" Grid.Row="0" Grid.Column="0" />
<TextBox Text="Test" Grid.Row="0" Grid.Column="1" />
<TextBox Text="Test" Grid.Row="0" Grid.Column="2" />
<TextBox Text="Test" Grid.Row="1" Grid.Column="0" />
<TextBox Text="Test" Grid.Row="1" Grid.Column="1" />
<TextBox Text="Test" Grid.Row="1" Grid.Column="2" />
<TextBox Text="Test" Grid.Row="2" Grid.Column="0" />
<TextBox Text="Test" Grid.Row="2" Grid.Column="1" />
<TextBox Text="Test" Grid.Row="2" Grid.Column="2" />
</Grid>
依赖属性
public class GridProperties
{
#region RowCount Property
/// <summary>
/// Adds the specified number of Rows to RowDefinitions. Default Height is Auto
/// </summary>
public static readonly DependencyProperty RowCountProperty =
DependencyProperty.RegisterAttached("RowCount", typeof(int),
typeof(GridProperties),
new PropertyMetadata(-1, RowCountChanged));
// Get
public static int GetRowCount(DependencyObject obj)
{
return (int)obj.GetValue(RowCountProperty);
}
// Set
public static void SetRowCount(DependencyObject obj, int value)
{
obj.SetValue(RowCountProperty, value);
}
// Change Event - Adds the Rows
public static void RowCountChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
if (!(obj is Grid) || (int)e.NewValue < 0)
return;
Grid grid = (Grid)obj;
grid.RowDefinitions.Clear();
for (int i = 0; i < (int)e.NewValue; i++)
grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
//SetStarRows(grid);
}
#endregion
#region ColumnCount Property
/// <summary>
/// Adds the specified number of Columns to ColumnDefinitions. Default Width is Auto
/// </summary>
public static readonly DependencyProperty ColumnCountProperty =
DependencyProperty.RegisterAttached("ColumnCount", typeof(int),
typeof(GridProperties),
new PropertyMetadata(-1, ColumnCountChanged));
// Get
public static int GetColumnCount(DependencyObject obj)
{
return (int)obj.GetValue(ColumnCountProperty);
}
// Set
public static void SetColumnCount(DependencyObject obj, int value)
{
obj.SetValue(ColumnCountProperty, value);
}
// Change Event - Add the Columns
public static void ColumnCountChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
if (!(obj is Grid) || (int)e.NewValue < 0)
return;
Grid grid = (Grid)obj;
grid.ColumnDefinitions.Clear();
for (int i = 0; i < (int)e.NewValue; i++)
grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
// SetStarColumns(grid);
}
#endregion
}
结果