开发者

Can't bind the content of a contentPresenter

开发者 https://www.devze.com 2023-03-19 11:06 出处:网络
I can\'t figure out what I\'m missing here. I want to bind the content of a ContentPresenter to a UIElement. I\'m doing something like this:

I can't figure out what I'm missing here. I want to bind the content of a ContentPresenter to a UIElement. I'm doing something like this:

<Window.Resources>
    <DataTemplate x:Key="container">
        <Border>
            <!--<TextBlock Text="A"/>-->
            <ContentPresenter Content="{Binding Element}" />
  开发者_开发问答      </Border>
    </DataTemplate>
</Window.Resources>
<ContentControl DataContext="{Binding}" ContentTemplate="{StaticResource container}" />

In MainWindow.cs

UIElement Element { get; set; }

public MainWindow()
{
    Element = new TextBox() { Text = "A" };
    DataContext = this;
    InitializeComponent();
}

I can put the textBlock in directly, but when I try the ContentPresenter it does not display anything.


ContentTemplate is a template for content. So, in the case of ContentControl, Content becomes DataContext of the DataTemplate. But you can't set Window as Content and the property you bind to has to be public.

So, after making Element public property and changing the XAML to:

<Window.Resources>
    <DataTemplate x:Key="container">
        <Border>
            <ContentPresenter Content="{Binding}" />
        </Border>
    </DataTemplate>
</Window.Resources>
<ContentControl Content="{Binding Element}" ContentTemplate="{StaticResource container}" />

“A” is shown in the window.

I'm assuming this isn't the real code where you encountered the issue, but doing something like this looks very odd. Maybe you should rethink your design.

0

精彩评论

暂无评论...
验证码 换一张
取 消