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:
我无法弄清楚我在这里缺少什么。我想将ContentPresenter的内容绑定到UIElement。我正在做这样的事情:
<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
在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.
我可以直接放入textBlock,但是当我尝试ContentPresenter时它不会显示任何内容。
1 个解决方案
#1
7
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.
ContentTemplate是内容的模板。因此,在ContentControl的情况下,Content成为DataTemplate的DataContext。但是您不能将Window设置为Content,并且绑定的属性必须是公共的。
So, after making Element
public property and changing the XAML to:
因此,在创建Element公共属性并将XAML更改为:
<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.
窗口中显示“A”。
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.
我假设这不是你遇到问题的真实代码,但做这样的事情看起来很奇怪。也许你应该重新考虑你的设计。
#1
7
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.
ContentTemplate是内容的模板。因此,在ContentControl的情况下,Content成为DataTemplate的DataContext。但是您不能将Window设置为Content,并且绑定的属性必须是公共的。
So, after making Element
public property and changing the XAML to:
因此,在创建Element公共属性并将XAML更改为:
<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.
窗口中显示“A”。
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.
我假设这不是你遇到问题的真实代码,但做这样的事情看起来很奇怪。也许你应该重新考虑你的设计。