gpt4 book ai didi

c# - 使用 MVVM 的可变网格行数

转载 作者:行者123 更新时间:2023-12-03 10:13:48 25 4
gpt4 key购买 nike

我需要控制网格中的行数。
在不使用 MVVM 模式的情况下,我通过代码隐藏实现了这一点,这样:

<UserControl>
<Grid x:Name="PART_Host" />
</UserControl>

private void UpdateHost(int rowCount) {
PART_Host.RowDefinitions.Clear();
PART_Host.Children.Clear();

for (int i = 1; i <= rowCount; i++) {
PART_Host.RowDefinitions.Add(new RowDefinition());
Grid.SetRow(PART_Host.Children[index], i - 1);
}
}

现在,我需要使用 MVVM 模式来执行此操作。我可以在我的 ViewModel 中访问所需的 rowCount 属性,但是如何在该属性更改时更新 View ?

谢谢 !

最佳答案

您是否尝试过附加属性?我不确定,但你可以这样做:

    public class GridExtensions
{
public static Int32 GetGridRowCount(DependencyObject obj)
{
return (Int32)obj.GetValue(GridRowCountProperty);
}

public static void SetGridRowCount(DependencyObject obj, UIElementCollection value)
{
obj.SetValue(GridRowCountProperty, value);
}

// Using a DependencyProperty as the backing store for GridRowCount. This enables animation, styling, binding, etc...
public static readonly DependencyProperty GridRowCountProperty =
DependencyProperty.RegisterAttached("GridRowCount", typeof(Int32), typeof(Grid), new FrameworkPropertyMetadata(OnGridRowCountChanged));

public static void OnGridRowCountChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue != null && obj is Grid)
{
Int32 rowCount = (Int32)e.NewValue;
Grid grid = (Grid)obj;

grid.RowDefinitions.Clear();
grid.Children.Clear();

for (int i = 1; i <= rowCount; i++)
{
grid.RowDefinitions.Add(new RowDefinition());
Grid.SetRow(grid.Children[index], i - 1);
}
}
}
}

并像这样使用它:
<Grid local:GridExtensions.GridRowCount="10"></Grid>

关于c# - 使用 MVVM 的可变网格行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3156602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com