foo*_*foo 1 c# data-binding wpf xaml
我无法弄清楚我在这里缺少什么.我想将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}" />
Run Code Online (Sandbox Code Playgroud)
在MainWindow.cs中
UIElement Element { get; set; }
public MainWindow()
{
Element = new TextBox() { Text = "A" };
DataContext = this;
InitializeComponent();
}
Run Code Online (Sandbox Code Playgroud)
我可以直接放入textBlock,但是当我尝试使用ContentPresenter时它不会显示任何内容.
ContentTemplate是内容的模板.因此,在的情况下ContentControl,Content变DataContext的DataTemplate.但是你不能设置Window为Content,你绑定的属性必须是公共的.
因此,在制作Element公共财产并将XAML更改为:
<Window.Resources>
<DataTemplate x:Key="container">
<Border>
<ContentPresenter Content="{Binding}" />
</Border>
</DataTemplate>
</Window.Resources>
<ContentControl Content="{Binding Element}" ContentTemplate="{StaticResource container}" />
Run Code Online (Sandbox Code Playgroud)
窗口中显示"A".
我假设这不是你遇到问题的真实代码,但做这样的事情看起来很奇怪.也许你应该重新考虑你的设计.