tags:

views:

33

answers:

2

Hello,

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.RowDefinitions.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 !

+1  A: 

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...

ArsenMkrt
I think I'll have to create my own ItemsControl. Thanks ;)
Aurélien Ribon
+4  A: 

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(new PropertyChangedCallback(OnGridRowCountChenged)));

        public static void OnGridRowCountChenged(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>
decyclone
Good way to do that too!
ArsenMkrt
That's a really nice solution ! But I need to insert controls in each row, and the overhead is just too much at the end. Thank you !
Aurélien Ribon