wpf 如何绑定到 ContentControl 的数据模板中的数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15389142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Bind To Data within a Datatemplate of a ContentControl
提问by markus s
I have the following simplified Example:
我有以下简化示例:
<Window x:Class="TemplateBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary
Source="pack://application:,,,/TemplateBinding;component/PersonTemplate.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<ContentControl ContentTemplate="{StaticResource PersonTemplate}" />
</Grid>
</Window>
With:
和:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DataTemplate x:Key="PersonTemplate">
<Border Width="100" Height="100" Background="RosyBrown">
<TextBlock Text="{Binding Path=FirstName}" VerticalAlignment="Center" TextAlignment="Center"/>
</Border>
</DataTemplate>
</ResourceDictionary>
as my DataTemplate in a separate ResourceDictionary file.
作为我在单独的 ResourceDictionary 文件中的 DataTemplate。
I set my DataContext in the Construcor of my MainWindow and have verified it by just displaying the first name like this: <ContentControl Grid.Row="1" Content="{Binding FirstName}"/>
.
我把我的DataContext在我的主窗口的Construcor并通过只显示这样的名字验证它:<ContentControl Grid.Row="1" Content="{Binding FirstName}"/>
。
In an other scenario wher I use a DataTemplate with a ListBox
I do the Binding exactly the same way in my DataTemplate and it just works.
在另一种情况下,当我使用 DataTemplate 时,ListBox
我在我的 DataTemplate 中以完全相同的方式进行绑定,并且它只是有效。
I know that the DataTemplate is working except the binding because it correctly shows the size and background color.
我知道除了绑定之外 DataTemplate 正在工作,因为它正确显示了大小和背景颜色。
What am I doing wrong? How would the Binding in my DataTemplate have to look?
我究竟做错了什么?我的 DataTemplate 中的 Binding 必须看起来如何?
回答by Jehof
You need to bind the Content
property of the ContentControl
您需要绑定的Content
属性ContentControl
<ContentControl Content="{Binding}" ContentTemplate="{StaticResource PersonTemplate}" />
This will set the DataContext of the ContentControl as Content of the control.
这会将 ContentControl 的 DataContext 设置为控件的内容。
Setting only the ContentTemplate
property is not enough. The ContentControl does not implicitly use its DataContext as Content.
仅设置ContentTemplate
属性是不够的。ContentControl 不会隐式地将其 DataContext 用作内容。