2016-04-28 161 views
0

我有如下定義自定義屬性自己的自定義控制:C#WPF引用自定義控制XAML中自定義屬性值

public partial class MyControl : UserControl 
{ 
    public CustomProperty X 
    { 
     get { return (CustomProperty) GetValue(XProperty); } 
     set { SetValue(XProperty, value); } 
    } 

    public static readonly DependencyProperty XProperty = DependencyProperty.Register(
     "X", typeof (CustomProperty), typeof (MyControl), null); 

    public MyControl() 
    { 
     InitializeComponent(); 
    } 
} 

假設我在XAML中設置X值是這樣的:

<controls:MyControl X="{Binding CustomPropertyValue}" /> 

我怎樣才能在MyControl XAML代碼訪問,如果它是這樣定義的X的值:

<UserControl> 
    <Button Content="<!--What to put here to access X?-->" /> 
</UserControl> 
+0

試試這個''。 – XAMlMAX

回答

1

你想從它內部綁定到UserControl的屬性。這樣做的最簡單方法是使用「的ElementName」結合的方法(通常Visual Studio的名稱,這些「用戶控件」),所以你會擁有:

<Button Content="{Binding MyProperty, ElementName=userControl}"/> 

我永遠記得這個時候,我開始的,但如果你點擊在設計師的小框,然後選擇「創建數據綁定」你可以通過一個很好的嚮導結合:

enter image description here

讓你可以買性關中控制所有元素。下面是一個例子結合使用的ElementName被稱爲「說明」的屬性:

enter image description here

值得注意的是,我發現這個經常需要構建之前列表中包含新的自定義依賴屬性。

這是一個很好的界面,用於探索如何以各種方式創建綁定。你很可能也與「FindAncestor」而不是「的ElementName」做到這一點,沿東西線結束:

<Button Content="{Binding Description, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MyCustomControlType}}}"/> 

但命名可能是更加容易和高效。