2010-10-07 68 views
0

在我的用戶界面中,我有時希望將標題放在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」?

回答

0

解決方案到目前爲止是爲類型名添加一個字符串屬性的視圖模型,並與填補這一代碼隱藏中的AutomationProperties.Name的內容。並使用以下綁定:

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

不過,我仍然認爲這應該可以做到這一點,而無需使用視圖模型,我希望能夠在我的數據綁定的技能提高了重新審視這個問題。

0

怎麼會在你的數據對象的路線:

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

相關問題