MVVM的可变网格行数

时间:2010-07-01 09:42:02

标签: c# wpf mvvm

我需要控制网格中的行数。 在不使用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?

谢谢!

2 个答案:

答案 0 :(得分:4)

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

    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>

答案 1 :(得分:1)

如果RowDefinition是依赖属性,则可以创建属性RowDefinition [] RowDefinitions,并返回RowCount长度的rowdefinitions数组,并将该数组绑定到RowDefinition属性,如果没有,则应创建usercontrol,使用ItemsControl显示你想要什么...