2011-07-08 39 views
1

我無法弄清楚我在這裏失蹤的內容。我想將ContentPresenter的內容綁定到UIElement。我在做這樣的事情:無法綁定contentPresenter的內容

<Window.Resources> 
    <DataTemplate x:Key="container"> 
     <Border> 
      <!--<TextBlock Text="A"/>--> 
      <ContentPresenter Content="{Binding Element}" /> 
     </Border> 
    </DataTemplate> 
</Window.Resources> 
<ContentControl DataContext="{Binding}" ContentTemplate="{StaticResource container}" /> 

在MainWindow.cs

UIElement Element { get; set; } 

public MainWindow() 
{ 
    Element = new TextBox() { Text = "A" }; 
    DataContext = this; 
    InitializeComponent(); 
} 

我可以把文本塊直接,但是當我嘗試ContentPresenter它不會顯示任何內容。

回答

7

ContentTemplate內容的模板。因此,在ContentControl的情況下,Content變爲的DataContext。但是您不能將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}" /> 

「A」顯示在窗口中。

我假設這不是真正的代碼,你遇到這個問題,但做這樣的事情看起來很奇怪。也許你應該重新考慮你的設計。

+0

好吧!第一個問題是「元素」不公開。第二個問題是ContentControl沒有「內容」,因此ContentTemplate沒有內容可以使用該模板。 – Scott