2010-11-05 66 views
0

我有一个属性网格控件,有许多单元格编辑器可以自动使用CellEditorTemplateSelector进行应用。每个属性网格行都绑定一个简单的PropertyItemViewModel。如何将DataGridTemplateColumn绑定到列值而不是行值?

现在,我试图重用所有这些单元格编辑器,并将其呈现在DataGrid中,以便能够并排比较多个对象值。因此,我添加了一个PropertiesRow对象,其中包含一个PropertyItemViewModel(与上述属性网格相同)的列表。

为了呈现每个单元格,我有一个简单的数据模板,它使用与属性网格相同的模板选择器。

<DataTemplate x:Key="CellDataTemplate"> 
    <ContentControl 
     Content="{Binding Mode=OneWay}" 
     ContentTemplateSelector="{StaticResource CellEditorTemplateSelector}" />    
</DataTemplate> 

然而,对于这项工作,模板期望一个PropertyItemViewModel(不是PropertiesRow),所以我必须通过绑定获取从PropertiesRow.PropertyItems[columnIndex]正确的以某种方式给它。所以,当我通过代码添加列,我想是这样的:

void AddColumns() 
{ 
    foreach (Property shownProperty in _ShownProperties) 
    { 
     _DataGrid.Columns.Add(new DataGridTemplateColumn() 
     { 
      Header = shownProperty.Name; 
      Binding = new Binding("PropertyItems[" + index + "]"); 
      CellTemplate = (DataTemplate) FindResource("CellDataTemplate"); 
     }); 
    } 
} 

然而,DataGridTemplateColumn没有绑定属性!所以我试图为每一列生成一个中间的DataTemplate,但是这开始变得非常复杂,我觉得必须有一个更简单的方法来做到这一点。

有什么建议吗?

回答

0

我找到了一个方法来做到这一点,它不是由MVVM标准清理,因为它直接与DataGridCells一起玩,但它在其他情况下工作正常。

我离开细胞模板原样,除了代替离开它绑定到我PropertiesRow对象,它没有哪列的指示我们在,我结合使用相对源结合到母体DataGridCell:

<DataTemplate x:Key="CellDataTemplate"> 
    <ContentControl 
     Content="{Binding Mode=OneWay, 
    RelativeSource={RelativeSource FindAncestor, 
           AncestorType={x:Type Controls:DataGridCell}}, 
    Converter={StaticResource CellToColumnValueConverter}}}" 
     ContentTemplateSelector="{StaticResource CellEditorTemplateSelector}" />    
</DataTemplate> 

我然后加入一个CellToColumnValueConverter它接受DataGridCell和使用该列的索引其变换成一个PropertyItem:

public class CellToColumnValueConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     DataGridCell cell = (DataGridCell) value; 
     int displayIndex = cell.Column.DisplayIndex; 
     PropertiesRow r = (PropertiesRow) cell.DataContext; 
     return r.PropertyItems[displayIndex]; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 
2

我有麻烦与上述XAML但我得到这个工作。必须设置Path=''或编译器不满意。

Content="{Binding Mode=OneWay, Path='', 
        RelativeSource={RelativeSource FindAncestor, AncestorType=DataGridCell, 
            AncestorLevel=1}, 
        Converter={StaticResource CellToColumnValueConverter}}" 
相关问题