2010-11-05 35 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}}" 
相關問題