2012-02-23 41 views
2

我想用依賴屬性實現一個usercontrol。這是我的問題;我想設置一個依賴項屬性與佈局子或我的用戶控件的子項。這是可能的嗎?怎麼做?如何實現內部內容依賴屬性?

<custom:myControl1> 
     <Label>Controls</Label> 
     <Label>I want</Label> 
     <Label>to set</Label> 
     <Label>as the dependency property</Label> 
     <Button Content="Is it possible?" /> 
    </custom:myControl1> 

回答

12

是的,在你的UserControl的XAML聲明ContentControl
使其在UserControl的代碼隱藏中將其Content屬性綁定到DependencyProperty
在您的UserControl類的頂部添加屬性:[ContentProperty("Name_Of_Your_Dependency_Property")]

然後你可以像你在你的問題那樣精確地做。該屬性定義了默認的依賴項屬性,因此您不必指定<custom:myControl1.MyDP>

喜歡的東西:

[ContentProperty("InnerContent")] 
public class MyControl : UserControl 
{ 
    #region InnerContent 
     public FrameworkElement InnerContent 
     { 
      get { return (FrameworkElement)GetValue(InnerContentProperty); } 
      set { SetValue(InnerContentProperty, value); } 
     } 

     // Using a DependencyProperty as the backing store for InnerContent. This enables animation, styling, binding, etc... 
     public static readonly DependencyProperty InnerContentProperty = 
      DependencyProperty.Register("InnerContent", typeof(FrameworkElement), typeof(MyControl), new UIPropertyMetadata(null)); 
     #endregion 
} 

<UserControl ...> 
    <ContentControl Content="{Binding InnerContent, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" /> 
</UserControl> 
+0

如果能控制從繼承你做的一樣?由於某種原因,我無法完成工作? – 2014-07-22 21:13:43