小编use*_*211的帖子

如何为DataGrid中的DataGridTemplateColumn创建可重用的CellTemplate?(仅XAML)

我一直在寻找我希望对这个问题的解决方案非常简单的方法,但是尽管我在stackoverflow上发现了很多其他问题,这些问题似乎也提出了类似的问题,并给出了一些建议的答案,但我一直在研究这些问题。全部,答案要么不起作用,要么实际上不回答问题。

我有一个带有几列的WPF DataGrid,我将其设置为DataGridTemplateColumns,如下所示:

<DataGridTemplateColumn Header="Price 1" Width="60">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ContentPresenter Content="{Binding Price1}" ContentTemplate="{StaticResource NumericCellDataTemplate}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

<DataGridTemplateColumn Header="Price 2" Width="60">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ContentPresenter Content="{Binding Price2}" ContentTemplate="{StaticResource NumericCellDataTemplate}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

<DataGridTemplateColumn Header="Price 3" Width="60">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ContentPresenter Content="{Binding Price3}" ContentTemplate="{StaticResource NumericCellDataTemplate}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
Run Code Online (Sandbox Code Playgroud)

我定义了一个可重用的DataTemplate,称为“ NumericCellDataTemplate”,它为每个列提供了一些通用功能,包括数字格式,对齐方式和值更改时的背景突出显示。请注意,这全部是由我在ViewModel中定义的一些特殊属性驱使的:

<DataTemplate x:Key="NumericCellDataTemplate">
    <Border Name="cellBorder" BorderThickness="0" BorderBrush="Transparent">
        <Border.Style>
            <Style TargetType="{x:Type Border}">
                <Style.Setters>
                    <Setter Property="Background" Value="Transparent" />
                </Style.Setters>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsRecentlyChanged}" Value="True">
                        <DataTrigger.EnterActions>
                            <BeginStoryboard Storyboard="{StaticResource IsRecentlyChangedEnterStoryboard}" />
                        </DataTrigger.EnterActions>
                        <DataTrigger.ExitActions>
                            <BeginStoryboard Storyboard="{StaticResource …
Run Code Online (Sandbox Code Playgroud)

c# wpf xaml wpfdatagrid

5
推荐指数
0
解决办法
1616
查看次数

标签 统计

c# ×1

wpf ×1

wpfdatagrid ×1

xaml ×1