在代码隐藏中创建内容控件

Create contentcontrol in code behind

如何在代码中使用contentcontrol创建如下边框?

<Border Name="Test">
        <ContentControl ContentTemplate="{StaticResource _cardDataTemplate}" Content="{Binding}"/>
</Border>

我正在使用以下代码,但未应用数据模板:

Border newCard = new Border();
newCard.Child = new ContentControl()
{
    ContentTemplate = CardDataTemplate
};

CardDataTemplate 已分配,据我所知这不是问题。

在您的情况下,您需要为内容 属性 创建到 DataContext(XAML 中的 Content="{Binding}")的绑定。您可以通过编写以下代码来完成:

BindingOperations.SetBinding(yourContentControlInstance, ContentControl.ContentProperty, new Binding());