简体   繁体   中英

Multiple Bindings to DataGrid Column

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?

您可以使用DataGridTemplate列,其中包含两个不同的控件,每个控件都绑定到一个不同的属性。

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM