Mikhail
Mikhail

Reputation: 3746

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>

Upvotes: 0

Views: 1954

Answers (1)

Joe
Joe

Reputation: 7004

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:

enter image description here

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

enter image description here

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.

Upvotes: 1

Related Questions