WPF 后台创建 DateTemplate

WPF 后台创建 DateTemplate

WPF 编程中,我们通常都是在前台 XAML 中通过标记语言来编写 DataTemplate 的。曾今有小伙伴在 Stack Overflow 上提问,如何在后台通过 C# 代码来创建 DataTemplate ?我搜索了一番,找到了 FrameworkElementFactory 类,它便是生成 DataTemplate 的核心功臣。

先看一下 XAML 中实现的效果:

<Grid x:Name="RootGrid">
    <DataGrid x:Name="MyDataGrid" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTemplateColumn>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Foreground="Red" Text="{Binding ValueA}"/>
                            <TextBlock Foreground="Blue" Text="{Binding ValueB}" />
                        </StackPanel>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

XAML 中的效果用 C# 来实现:

public MainWindow()
{
    InitializeComponent();
    InitializeDataGrid();
}

private void InitializeDataGrid()
{
    // StackPanel and Children
    var stackPanelFactory = new FrameworkElementFactory(typeof(StackPanel));
    stackPanelFactory.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);

    var textBlockFactoryA = new FrameworkElementFactory(typeof(TextBlock));
    textBlockFactoryA.SetValue(TextElement.ForegroundProperty, Brushes.Red);
    textBlockFactoryA.SetBinding(TextBlock.TextProperty, new Binding("ValueA"));

    var textBlockFactoryB = new FrameworkElementFactory(typeof(TextBlock));
    textBlockFactoryB.SetValue(TextElement.ForegroundProperty, Brushes.Blue);
    textBlockFactoryB.SetBinding(TextBlock.TextProperty, new Binding("ValueB"));

    stackPanelFactory.AppendChild(textBlockFactoryA);
    stackPanelFactory.AppendChild(textBlockFactoryB);

    // DataTemplate
    var dataTemplate = new DataTemplate
    {
        VisualTree = stackPanelFactory
    };

    // DataGridTemplateColumn
    var templateColumn = new DataGridTemplateColumn
    {
        CellTemplate = dataTemplate
    };

    _dataGrid.Columns.Add(templateColumn);

    // DataGrid
    _dataGrid.Name = "MyDataGrid";
    _dataGrid.AutoGenerateColumns = false;

    // Add the DataGrid into RootGrid
    RootGrid.Children.Add(_dataGrid);
}

private readonly DataGrid _dataGrid = new DataGrid();
  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ironyho

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值