通过ContentControl绑定到DataTemplate中根元素的属性

问题描述:

在我的用户界面中,我有时希望将标题放在usercontrols上方。通过ContentControl绑定到DataTemplate中根元素的属性

我想在XAML中声明这些标题以便将来定位,所以我想让它们远离datacontexts。

数据绑定是否可以从usercontrol的根节点上设置的属性中获取它们?

我煮完问题,下到下面的代码示例:

using System.Windows; 

namespace WpfApplication12 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 

      this.Person = new Author { Name = "Guge" }; 

      this.DataContext = this; 
     } 

     public object Person { get; set; } 
    } 

    public class Author 
    { 
     public string Name { get; set; } 
    } 
} 

和:

<Window x:Class="WpfApplication12.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:WpfApplication12" 
    Title="MainWindow" Height="350" Width="525"> 
<Window.Resources> 
    <DataTemplate DataType="{x:Type local:Author}"> 
     <Border AutomationProperties.Name="Author" BorderThickness="1" BorderBrush="Black"> 
      <Label Content="{Binding Name}"/> 
     </Border> 
    </DataTemplate> 
</Window.Resources> 
<StackPanel> 
    <Label x:Name="Position" Content="Author"/> 
    <ContentControl x:Name="presentation" Content="{Binding Person}"/> 
</StackPanel> 

和现实的问题是:我怎么能在内容使用数据绑定“位置”标签的属性从DataTemplate中Border的AutomationProperties.Name属性中获取单词“Author”?

解决方案到目前为止是为类型名添加一个字符串属性的视图模型,并与填补这一代码隐藏中的AutomationProperties.Name的内容。并使用以下绑定:

<StackPanel> 
    <Label x:Name="Position" Content="{Binding Person.TypeName}"/> 
    <ContentControl x:Name="presentation" Content="{Binding Person}"/> 
</StackPanel> 

不过,我仍然认为这应该可以做到这一点,而无需使用视图模型,我希望能够在我的数据绑定的技能提高了重新审视这个问题。

怎么会在你的数据对象的路线:

public class Author 
{ 
    public string Name { get; set; } 
    public string TypeName { get; set; } // might be better in base class Person 
} 

和:

<Window.Resources> 
    <DataTemplate DataType="{x:Type local:Author}"> 
     <Border AutomationProperties.Name="{Binding TypeName}" 
       BorderThickness="1" BorderBrush="Black"> 
      <Label Content="{Binding Name}"/> 
     </Border> 
    </DataTemplate> 
</Window.Resources> 
<StackPanel> 
    <Label x:Name="Position" Content="{Binding ElementName=presentation, Path=DataContext.TypeName}"/> 
    <ContentControl x:Name="presentation" Content="{Binding Person}"/> 
</StackPanel> 
+0

谢谢。我想在代码隐藏中将TypeName设置为AutomationProperties.Name的内容? – Guge 2010-10-08 08:44:57

+0

必须有一些地方设置Person.TypeName,是的。一般来说,我不喜欢codebhind(http://goo.gl/KyTW)。但如果你使用它,那可能就是这个地方。 – bitbonk 2010-10-08 11:48:17

+0

TypeName的数据绑定表达式不起作用。 – Guge 2010-10-23 12:44:32