Silverlight / WPF - DataGrid with variable number of columns?

Asked By Ahmad
11-Aug-10 07:19 PM
Basically, if you use MVVM you bind your datagrid to a collection of objects, each row represents an object and each column represents a property in that object.
But if you want it such that the number of columns is variable, and editable, that is impossible because the number of properties (which columns represent) in any class is fixed.
I wish I can bind the datagrid to a 2 dimentsional array or a collection of collections of values, such that:

adding a collection to the outer collection will add a row to the grid 
and adding a value to an inner collection will add another column to the grid.

(Imagine a senario where every column represents a date and every row represents a currency and every cell represents the exchange rate of that currency in that date, and you want to dynamically change the number of columns (dates) and their range using MVVM pattern...

Please Help
  Christopher replied to Ahmad
17-Aug-10 01:18 PM
Hi Ahmad

I have exactly the same problem in that the app has no Idea of how many columns  or rows I have until after user data is loaded so they ave to be loaded dynamically.

Did you perhaps find a solution to your problem?

Chris
  Ahmad replied to Christopher
17-Aug-10 05:06 PM
Hello Chris,

I have found a solution, though probably not very elegant.
First I define a new useful class called ObservableDictionary like so (I put it in the utilities folder in my project)


class ObservableDictionary<TKey, TValue> : IDictionary<TKey, TValue>, INotifyCollectionChanged
{
  // Implementation
}


This observable dictionary is just like normal dictionary except it implements INotifyCollectionChanged and so is suitable for binding.
Second I store the data in my view-model as a 2 dimension ObservableDictionary like this:

public ObservableDictionary<string, ObservableDictionary<string,double> Data { set; get; }


You access your data like this: Data[rowHeader][columnHeader].
Third I define an extension method in my View source file called GenerateColumns like so:


public static void GenerateColumns(this DataGrid datagrid,
  ObservableDictionary<string, ObservableDictionary<string, double> data)
{
  datagrid.Columns.Clear();
  if (data.Count == 0) return;
  datagrid.ItemsSource = data;
 
  foreach (string columnHeader in data.First().Value.Keys)
  {
    DataGridTextColumn column = new DataGridTextColumn
    {
    Header = columnHeader,
    Binding = new Binding(String.Format("Value[{0}]", columnHeader))
    Width = 80
  };
     datagrid.Columns.Insert(0, column);
  }
}


You pass a reference of your data to that method like this:

MyDataGrid.GenerateColumns( ((ViewModelClass)DataContext).Data );

and your columns will be generated and bound to the Data in the view-model.
For this to work, you need to take care of few things:
1 - In your view-model (where Data is) you should handle CollectionChangedEvent by raising onPropertyChanged("Data") in your view-model class.
2 - you should handle PropertyChanged raised earlier in your view by calling 
GenerateColumns(((ViewModelClass)DataContext).Data)
3 - Make sure not call these if your View's DataContext == null, you can do this by adding this method to your view class

protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
  base.OnPropertyChanged(e);
  if (e.Property.Name == "DataContext")
  {
    ((ViewModelClass)DataContext).PropertyChanged += HandlerThatCallsGenerateColumns;
  }
}
 
void HandlerThatCallsGenerateColumns(object sender, PropertyChangedEventArgs e)
{
  if (e.PropertyName == "Data")
  {
    MyDataGrid.GenerateColumns(((ViewModelClass)DataContext).Data);
  }
}


Tell me how it goes...

Regards,
Ahmad
  Christophe Scherly replied to Ahmad
18-Feb-11 10:55 AM
Hello Ahmad,

I'm very interesting to implement your solution but until now I was unsuccessful.
Do you have a complete solution using your technique?

Create New Account
help
SilverLight What is SilverLight, its concept, why to use it and how to use it What is Silverlight? Silverlight is a new cross-browser, cross-platform implementation of the .NET Framework for building and browsers, including Microsoft Internet Explorer, Mozilla Firefox, Apple Safari, Opera. The plugin required to run Silverlight is very small in size hence gets installed very quickly. It is combination of different platform that allows you to select tools and the programming language you want to use. Silverlight integrates seamlessly with your existing Javascript and ASP.NET AJAX code to complement functionality which you have already created. Silverlight aims to compete with Adobe Flash and the presentation components of Ajax . It also competes with Sun Microsystems' JavaFX, which was launched a few days after Silverlight. Currently there are 2 versions of Silverlight: Silverlight 1.0 : Silverlight 1.0 consists of
silverlight and wpf difference if one person has gain master in silverlight than wiil this help him in learning wpf Hi Malik, WPF has a more advanced and mature XAML support than Silverlight. Silverlight used to be called (WPF / E) and is a subset of the WPF XAML design well and other items. WPF is hardware accelerated and supports things like GPU shaders which Silverlight 2 does not. Silverlight 2 does have the VisualStateManager inside Blend 2, which I think WPF needs an add on and a tweak to work. I think that is the only case where Silverlight 2 XAML was / is slightly ahead of WPF's. Here is a link on XAML us / library / cc917841(VS.95).aspx Here is a good article on MSNMAG about designing Silverlight / WPF apps together and sharing code: http: / / msdn.microsoft.com / en-us / magazine / cc895632.aspx
View HTML files in silverlight Silverlight / WPF hi. . how to View HTML files in silverlight? via silverlight how to disable the right click option in html files? i.e)SL html viewer no, status = no, menubar = no, resizable = yes"); } } } Create New Account keywords: View, HTML, files, in, silverlight description: p style = border:0px;margin-bottom: 18px; border-image: initial; outline-width: 0px; outline
Silverlight What is the purpose of Silverlight? Why it is used? How can I use silverlight in my application? Any simple web example of silverlight with VS 2005 and .Net Framework 2.0 (not the Hellow world Application). ? I want to start with Silverlight and I am very new to Silverlight. What is Silverlight? Microsoft Silverlight is a web browser plugin that provides support for rich internet applications such as animation
Load swf files in silverlight Silverlight / WPF hi. . how to Load swf file in silverlight? need ur suggetsions with examples. . regards gopal.s There is a swf to xaml converter available http: / / theconverted.ca / And there are some silverlight carousel examples available http: / / silverlight.net / learn / learnvideo.aspx?video = 33734 Refer this link- http: / / forums silverlight.net / t / 79400.aspx Hi, As per my knowledge, you can not load the swf file directly to silverlight, you need to convert swf to silverlight format first. here are some useful links that help to convert the swf into your