Elex
Elex

Reputation: 77

WPF Binding to a property of a custom control

I've created a custom control, means a class deriving from control associating a default lookless theme defined via Themes/Generic.xaml. So far so good.

Now, I want to use the control like any other of the main WPF-controls (textbox, listbox, label, textblock, ...) and bind to the defined properties.

The custom control defines a property called Value, that I like to set a Binding to. But nothing ever is written to the bound property in the DataContext.

Well, here's what I've got so far:

In Custom Control class, there is as follows:

public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
    "Value", typeof(string), typeof(MyClass),
    new FrameworkPropertyMetadata("", new PropertyChangedCallback(onValuePropertyChangedCallback)));

private static void onValuePropertyChangedCallback(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
    MyClass myClass = (MyClass)sender;
    myClass.Value = (string)args.NewValue;
}

public string Value
{
    get { return (string) GetValue(ValueProperty); }
    set { SetValue(ValueProperty, value); }
}

When I use the control, it's like that

<local:MyClass MyValue="{Binding CurrentValue}" ... />

The CurrentValue-property of the DataContext is never affected, never changes it's value.

What am I doing wrong?

Upvotes: 2

Views: 3955

Answers (1)

Clemens
Clemens

Reputation: 128060

The Binding to should be two-way in order to update the source property:

<local:MyClass Value="{Binding CurrentValue, Mode=TwoWay}" ... />

If you want this to be the default binding mode, you could set an appropriate flag when you register your property:

public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
    nameof(Value), typeof(string), typeof(MyClass),
    new FrameworkPropertyMetadata(
        "", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

public string Value
{
    get { return (string)GetValue(ValueProperty); }
    set { SetValue(ValueProperty, value); }
}

Note that your onValuePropertyChangedCallback was entirely redundant. You don't need to set the property again, when its value has just changed.

Upvotes: 2

Related Questions