Glitch
Glitch

Reputation: 595

How to use a programmatic 'get' equivalent in a WPF dependency property?

Where this is the clr way of writing a property:

public byte Value
{
   get{
     return GetByteData();
   }
   set{
     SetByteData(value);
   }
}

I've read up on how to do the same the dependency property way, and this is all I could do by myself:

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

public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
    "Value", typeof(byte), typeof(MyControl),
    new FrameworkPropertyMetadata((byte)0, ValueChanged));

public static void ValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    byte r = (byte)e.NewValue;
    MyControl v = (MyControl)d;
    v.SetByteData(r);
}

With the examples I've looked at, from which I've made the above snippet, I can't find a place to put the GetByteData(), which calculates an output value for the current UI-state when the user interacts, so as to update the 'Value'.

Until previously I was putting it in the getter anyway like with clr, but I get the feeling that it's the wrong approach, but I could be wrong. Where should I be putting it? If not, what should be my approach? Is it at all possible to have a programmatic getter for a dependency property?

It's possible that I've been using the wrong keywords to look for a solution. Any help putting me in the right direction would be much appreciated. Thanks in advance.

Upvotes: 0

Views: 68

Answers (1)

Clemens
Clemens

Reputation: 128060

As long as it is only the source (and not the target) property of a Binding, as in

{Binding Value, ElementName=MyControlName}

and you don't want to apply a value by a Style Setter, or animate the value, the property does not need to be a dependency property.

Just implement INotifyPropertyChanged like this:

public partial class MyControl : UserControl, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public byte Value
    {
       get { return GetByteData(); }
       set
       {
           SetByteData(value);
           PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Value)));
       }
    }

    ...
}

Upvotes: 1

Related Questions