2011-08-23 75 views
4

我將DataGridCellTemplate中的ContentPresenter替換爲TextBlock,現在我搜索正確的內容Binding帶有TextBlock的WPF DataGridCell模板 - 綁定?

正常的方法是Text="{TemplateBinding Content}TextBlock - 它不起作用。 Text="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Content, Mode=TwoWay}"也不正確。

還有其他想法嗎?

+0

請注意,當Content是一個字符串時,ContentPresenter會自動生成一個TextBlock。 –

回答

12

假設你已經改變了DataGridCell Template以下

<ControlTemplate TargetType="{x:Type DataGridCell}"> 
    <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True"> 
     <TextBlock Text="{Binding}"/> 
     <!--<ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/> --> 
    </Border> 
</ControlTemplate> 

既然你刪除ContentPresenter,該DataGridCell沒有顯示其Content的方式。但它仍然存在。 DataGridCell.Content 是一個TextBlock包含您的原始TextTextBlockTemplate是另一個。

所以你會被綁定到的TemplatedParent

<TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent}, 
          Path=Content.Text}"/> 

Content.Text屬性,因此,概括起來得到正確的Text。 This works

<ControlTemplate TargetType="{x:Type DataGridCell}"> 
    <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True"> 
     <TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent}, 
            Path=Content.Text}"/> 
    </Border> 
</ControlTemplate> 
2

數據網格單元的數據上下文應該是數據本身。因此,結合應該簡單地:

<TextBlock Text="{Binding}"/> 
+4

DataGridCell與DataGridRow具有相同的DataContext,因此您需要一個路徑。如果你想這是通用的,你不能設置路徑。我不認爲這有效 –