简体   繁体   English

到DataGrid列的多个绑定

[英]Multiple Bindings to DataGrid Column

Is it possible to bind two different data to the same DataGrid column. 是否可以将两个不同的数据绑定到同一DataGrid列。 Say if I have class A which has the Property p1 and I have another class B with the Property p2. 假设我有一个具有属性p1的类A,而另一个具有属性p2的类B。 Is it possible to bind p1 and p2 to the same datagrid column? 是否可以将p1和p2绑定到同一datagrid列?

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

The simplest way to do this is probably a MultiBinding. 最简单的方法可能是MultiBinding。 Here is a simple example of how to use a MultiBinding (which takes advantage of the StringFormat property, which I like). 这是一个如何使用MultiBinding的简单示例 (它利用了我喜欢的StringFormat属性)。

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. 每个类型的属性到列的映射都必须位于某个地方,但是它不必位于XAML中,这不是我要提到的地方。 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: 假设我还没有ClassA和ClassB对象的视图模型类(并且我不想创建它们),我将实现以下内容:

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. ...然后将DataGrid的列绑定到DataGridHelper对象的集合。

If I did have ClassAViewModel and ClassBViewModel classes, I'd just implement Column1 , Column2 , etc. properties in both. 如果确实ClassAViewModelClassBViewModel类,则只需在这两个中都实现Column1Column2等属性。 That'd be the way to go if I needed to support two-way binding and validation. 如果我需要支持双向绑定和验证,那将是必经之路。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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