Wednesday, October 31, 2012

Binding the number of columns and rows of a Grid

Binding the number of columns and rows of a Grid

I have a WP7 app and so far, I have implemented within an MVVM framework.

I now want to extend this app and part of this involves a grid and I am not sure if I can do what I want to do via binding. Specifically

Will need a variable number of columns - I don't see how I can do this with binding. And if I can then I want to vary the width of the columns depending upon the number of columns

Same with the rows a variable number involved.

I can set up a VM with all the information required here, but I cannot see I can bind to the Grid to make it work. I also want to include some variable data within the grid and again, I cannot see how I can do this with binding. Worked well with a listbox where I have just bound to the collection of objects, but this is quite different.

Is this a case where I should just generate in the code behind? I am happy to do that... but would happily try and do it via binding if its possible.

  • thanks

Answers & Comments...

Answer: 1

You can extend the current Grid control and add some custom Dependency Properties (E.G. Columns and Rows) and bind to these. This would allow you to keep the MVVM pattern.

E.G.

public class MyGridControl : Grid {   public static readonly DependencyProperty RowsProperty =     DependencyProperty.Register("Rows", typeof(int), typeof(MyGridControl), new PropertyMetadata(RowsChanged));    public static readonly DependencyProperty ColumnsProperty = DependencyProperty.Register("Columns", typeof(int), typeof(MyGridControl), new PropertyMetadata(ColumnsChanged));    public static void RowsChanged(object sender, DependencyPropertyChangedEventArgs args)   {     ((MyGridControl)sender).RowsChanged();   }    public static void ColumnsChanged(object sender, DependencyPropertyChangedEventArgs args)   {     ((MyGridControl)sender).ColumnsChanged();   }    public int Rows   {     get { return (int)GetValue(RowsProperty); }     set { SetValue(RowsProperty, value); }   }    public int Columns   {     get { return (int)GetValue(ColumnsProperty); }     set { SetValue(ColumnsProperty, value); }   }    public void RowsChanged()       {     //Do stuff with this.Rows     //E.G. Set the Row Definitions and heights   }    public void ColumnsChanged()   {     //Do stuff with this.Columns     //E.G. Set the Column definitions and widths   } 

If your VM had the properties 'Rows' and 'Columns', the XAML would look like this:

<local:MyGridControl   Rows="{Binding Rows}"   Columns="{Binding Columns}"> </local:MyGridControl> 
by : wdavohttp://stackoverflow.com/users/807836




No comments:

Post a Comment

Send us your comment related to the topic mentioned on the blog