简体   繁体   中英

C# WPF reference custom property value inside custom control xaml

I have my own custom control with custom property defined as following:

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();
    }
}

Assuming I set X value in XAML like this:

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

How can I access value of X in MyControl XAML code if it is defined like this:

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

You want to bind it to the property of the UserControl from within it. Easiest way of doing this is using the "ElementName" binding method (often Visual studio names these "userControl") so you'll end up with:

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

I could never remember this when I started, but if you click the little box in the designer and select "create data binding" you can go through a nice wizard for binding:

在此处输入图片说明

Where you can pick properties off all the elements in the control. Here's an example binding to a property called "Description" using ElementName:

在此处输入图片说明

It is worth noting I've found this often needs a build before the list contains new custom dependency properties.

It's a nice interface for exploring how to create bindings in various ways. You could probably also do this with "FindAncestor" instead of "ElementName" and end up with something along the lines of:

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

But naming is probably easier and more efficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM