开发者

Variable grid row count with MVVM

I need to control the number of rows in a grid. Without using the MVVM pattern, I achieved this with code-behind, this way :

<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.RowDefini开发者_StackOverflow中文版tions.Add(new RowDefinition());
        Grid.SetRow(PART_Host.Children[index], i - 1);
    }
}

Now, I need to do this using the MVVM pattern. I can access the required rowCount property in my ViewModel, but how can I update the View when this property changes ?

Thanks !


Have you tried attached properties? I am not sure but you can do something like this :

    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);
                }
            }
        }
    }

And use it like :

<Grid local:GridExtensions.GridRowCount="10"></Grid>


If RowDefinition is dependency property, you can create a property RowDefinition[] RowDefinitions, and return an array of rowdefinitions with RowCount length, and bind that array to RowDefinition property, if not, you should create your usercontrol, using ItemsControl to show what you want...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜