[英]C# WPF reference custom property value inside custom control 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}" />
如果這樣定義X,我如何在MyControl
XAML代碼中訪問X的值:
<UserControl>
<Button Content="<!--What to put here to access X?-->" />
</UserControl>
您要從其中將其綁定到UserControl的屬性。 最簡單的方法是使用“ ElementName”綁定方法(Visual Studio通常將這些名稱命名為“ userControl”),因此您將得到以下結果:
<Button Content="{Binding MyProperty, ElementName=userControl}"/>
當我開始時,我永遠不會記住這一點,但是如果您單擊設計器中的小框並選擇“創建數據綁定”,則可以通過一個不錯的綁定向導:
您可以在其中選擇控件中所有元素的屬性。 這是一個使用ElementName綁定到名為“ Description”的屬性的示例:
值得注意的是,我發現這通常需要在列表包含新的自定義依賴項屬性之前進行構建。
這是一個很好的界面,用於探索如何以各種方式創建綁定。 您可能還可以使用“ FindAncestor”而不是“ ElementName”來執行此操作,最后得到類似以下內容的結果:
<Button Content="{Binding Description, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MyCustomControlType}}}"/>
但是命名可能更容易,更有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.