我在我的應用程序中使用WPF Toolkit的DataGrid控件。我需要用已調整的TextBlock替換用於單元格的默認TextBlock。 XAML代碼如下所示:ContentTemplate綁定問題
<Window.Resources>
<Style x:Key="cellStyle" TargetType="{x:Type tk:DataGridCell}">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock Background="Yellow" />
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<tk:DataGrid
ItemsSource="{Binding Path=Products}"
CellStyle="{StaticResource cellStyle}"
AutoGenerateColumns="False">
<tk:DataGrid.Columns>
<tk:DataGridTextColumn
Header="Id"
Binding="{Binding Path=Id}"/>
<tk:DataGridTextColumn
Header="Product"
Binding="{Binding Path=Name}"/>
</tk:DataGrid.Columns>
</tk:DataGrid>
</Grid>
在TextBlock替換之後,所有數據綁定都將丟失,並且所有單元都爲空。將屬性Text =「{Binding}」添加到新的TextBlock中並沒有幫助。在這種情況下,所有單元格都包含DataGridTestApp.Product類型的名稱。 TextBlock的正確綁定表達式是什麼?
P.S.以防萬一:MainWindowViewModel代碼
internal sealed class MainWindowViewModel
{
public MainWindowViewModel()
{
_products = new ObservableCollection<Product>()
{
new Product(1, "ProductName1"),
new Product(2, "ProductName2"),
new Product(3, "ProductName3"),
new Product(4, "ProductName4"),
new Product(5, "ProductName5"),
};
}
public ObservableCollection<Product> Products
{
get { return _products; }
}
private ObservableCollection<Product> _products;
}
謝謝。但這是我的問題的簡化例子。其實我需要將Margin屬性設置爲「0,5」的TextBlock。我可以爲DataGridCell設置Margin屬性,但對我來說不一樣。行選擇外觀會有所不同。 – vkrzv
不會設置contentpresenters填充/邊距具有相同的效果嗎? –
在這種情況下,選擇不包括邊距/填充。在相鄰選擇之間會有很大的差距。如果設置了TextBlock的邊距屬性,問題就解決了。 – vkrzv