代码之家  ›  专栏  ›  技术社区  ›  Aurelien Ribon

使用MVVM的变量网格行计数

  •  2
  • Aurelien Ribon  · 技术社区  · 15 年前

    我需要控制网格中的行数。 在不使用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中所需的行数属性,但是当此属性更改时,如何更新视图?

    谢谢!

    2 回复  |  直到 13 年前
        1
  •  1
  •   Arsen Mkrtchyan    15 年前

    如果rowdefinition是dependency属性,则可以创建属性rowdefinition[]rowdefinitions,并返回rowcount长度的rowdefinition数组,然后将该数组绑定到rowdefinition属性,否则,应使用itemscontrol创建用户控件以显示所需内容…

        2
  •  4
  •   Martin Liversage    13 年前

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

        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>