代码之家  ›  专栏  ›  技术社区  ›  Reflux

对DataGrid列的多个绑定

  •  0
  • Reflux  · 技术社区  · 14 年前

    是否可以将两个不同的数据绑定到同一个DataGrid列。假设我有一个类,它的属性是p1,我有另一个类,它的属性是p2。是否可以将p1和p2绑定到同一个datagrid列?

    3 回复  |  直到 14 年前
        1
  •  1
  •   Robert Rossney    14 年前

    像这样:

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

    每种类型的属性到列的映射都必须存在于某个地方,但它不必存在于XAML中,我不会把它放在这里。我会在我的视图模型中这样做。假设我还没有用于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; }
    }
    

    DataGrid 的列添加到 DataGridHelper 物体。

    如果我 ClassAViewModel ClassBViewModel 类,我只需要实现 Column1 , Column2 等属性。如果我需要支持双向绑定和验证,那就应该这样做。

        2
  •  2
  •   Rachel    14 年前

        3
  •  1
  •   Daniel Pratt    14 年前

    最简单的方法可能是多重绑定。这是一个 simple example 如何使用MultiBinding(它利用了我喜欢的StringFormat属性)。