tags:

views:

39

answers:

3

Is it possible to bind two different data to the same DataGrid column. Say if I have class A which has the Property p1 and I have another class B with the Property p2. Is it possible to bind p1 and p2 to the same datagrid column?

+2  A: 

You could use a DataGridTemplate column which would contain two different controls, each which are bound to a different property.

Rachel
+1  A: 

The simplest way to do this is probably a MultiBinding. Here is a simple example of how to use a MultiBinding (which takes advantage of the StringFormat property, which I like).

Daniel Pratt
+1  A: 

Something like this:

<StackPanel>
   <TextBlock Text="{Binding ClassAProperty}"/>
   <TextBlock Text="{Binding ClassBProperty}"/>
</StackPanel>

will work, so long as the classes don't have any properties with the same name. But that's a kind of ugly hack, and good luck finding real binding errors among all of the spurious binding errors that this approach will generate.

The mapping of each types' properties to columns has to live somewhere, but it doesn't have to live in XAML, and that's not where I'd put it. I'd do it in my view model. Assuming that I don't already have view model classes for my ClassA and ClassB objects (and that I don't want to create them), I'd implement something like this:

public class DataGridHelper
{
   public Wrapper(object o)
   {
      ClassA a = o as ClassA;
      if (a != null)
      {
         Column1 = a.Property1;
         Column2 = a.Property2;
         ...
      }

      ClassB b = o as ClassA;
      if (b != null)
      {
         Column1 = b.Property1;
         Column2 = b.Property2;
         ...
      }

      public object Column1 { get; private set; }
      public object Column2 { get; private set; }
}

...and then bind the DataGrid's columns to a collection of DataGridHelper objects.

If I did have ClassAViewModel and ClassBViewModel classes, I'd just implement Column1, Column2, etc. properties in both. That'd be the way to go if I needed to support two-way binding and validation.

Robert Rossney
Yea StackPanel is messy. Creating a DataGridHelper looks likes the way to go. Thanks!
Reflux