我有以下xaml代码。
<tk:DataGrid
ItemsSource="{Binding Path=Products}"
AutoGenerateColumns="False">
<tk:DataGrid.Columns>
<tk:DataGridTextColumn
Header="Id">
<tk:DataGridTextColumn.CellStyle>
<Style TargetType="{x:Type tk:DataGridCell}">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock Margin="0,10" Text="{Binding Path=Id}" />
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</tk:DataGridTextColumn.CellStyle>
</tk:DataGridTextColumn>
<tk:DataGridTextColumn
Header="Product">
<tk:DataGridTextColumn.CellStyle>
<Style TargetType="{x:Type tk:DataGridCell}">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock Margin="0,10" Text="{Binding Path=Name}" />
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</tk:DataGridTextColumn.CellStyle>
</tk:DataGridTextColumn>
</tk:DataGrid.Columns>
</tk:DataGrid>
如何摆脱复制粘贴?将其移动到资源的简单方法失败,因为Text =“{Binding Path = XYZ}”停止工作。
答案 0 :(得分:0)
我认为你不能在这里做你想做的事,即两个细胞都有一个模板定义。但是,使用DataGridTemplateColumn将取出一些XAML行(使用DataGridTextColumn然后覆盖其控件模板有点奇怪):
<DataGrid ItemsSource="{Binding Path=Products}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn Header="ID">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Margin="10,0" Text="{Binding Path=ID}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Name">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Margin="10,0" Text="{Binding Path=Name}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
还有另一种方法,这次使用DataGridTextColum,它可以给你一些接近你想要的东西:
<DataGrid Name="ui_datagrid" AutoGenerateColumns="False">
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Padding" Value="0,10"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Border Padding="{TemplateBinding Padding}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
<ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
</DataGrid.Columns>
</DataGrid>