2014-02-10 27 views
0

我想創建一個可以嵌入免費內容的用戶控件。UserControl嵌入免費的XAML內容

我創建了一個依賴屬性的內容:

public sealed partial class MyUserControl : UserControl 
{ 

    public Border MyProperty 
    { 
     get { return (Border)GetValue(MyPropertyProperty); } 
     set { SetValue(MyPropertyProperty, value); } 
    } 

    public static readonly DependencyProperty MyPropertyProperty = 
     DependencyProperty.Register("MyProperty", typeof(Border), typeof(VisitList), new PropertyMetadata(new Border() { Height=300, Width=300 })); 

... 
} 

所以在我MainPage.xaml中,我可以用下面的代碼使用它:

<MyUserControl> 
      <MyUserControl.MyProperty> 
       <Border x:Name="MyContent" Width="60" Height="60" Background="Pink"> 
        ... Whatever ... 
       </Border> 
      </MyUserControl.MyProperty>     
</MyUserControl> 

從此,我無法找到MyUserControl.xaml中的XAML語法用於聲明將在運行時由MyContent替代的佔位符。 我試圖與:

<UserControl ... > 
.... 
    <Grid ...> 

     <ContentPresenter Content="{TemplateBinding MyProperty}" /> 

    </Grid> 
</UserControl> 

但是,它與消息崩潰:

An exception of type 'Windows.UI.Xaml.Markup.XamlParseException' occurred in xXx.exe but was not handled in user code 
WinRT information: Failed to create a 'Windows.UI.Xaml.DependencyProperty' from the text 'MyProperty'. [Line: 29 Position: 35] 

(行:29的位置:35參照內容= 「{TemplateBinding myProperty的}」)

回答

1

它聽起來像是在混合模板控件和用戶控件。這有點複雜,但基本上,當TemplateBindings與控件的ContentTemplate分開時,與Content本身相反(我相信這是基於您所展示的xaml而發生的)。

試着改變你的綁定這樣:

<UserControl x:Name="RootControl" ...> 
.... 
    <ContentControl Content="{Binding MyProperty, ElementName=RootControl}" /> 
.... 
</UserControl> 

這意味着,你將需要有你的用戶控件執行INotifyPropertyChanged的情況下,它需要改變Content迴應。

+2

Nate說的是好的,但我也會做的是我將定義您的屬性爲'DataTemplate'類型而不是'Border',並使用'ContentControl.ContentTemplate'而不是'ContentControl.Content'來使用它。 –

+0

謝謝,Nate的建議很好。感謝Filip,我可以使用任何xaml代碼(而不是邊界) –