0

I need to run some custom code in a User Control when a certain custom dependency property (defined in a parent User Control) has changed. What is the best way to do this in WPF?

I have spent a good bit of time playing with triggers in XAML which use data binding to access my CDP, and found a solution which requires setting an intermediate CDP (in the child user control), and then running my custom code in that second CDP's changed event. However this is pretty messy and doesn't seem to be the proper use of WPF. Also the code I am running isn't directly related to the UI, so XAML doesn't seem to be appropriate here.

Assuming the child user control's DataContext is properly set such that I can access the CDP, how can I write code to simply execute a callback function when the CDP is changed?

I already have an "OnXXXChanged" callback in the high-level parent control, but that control doesn't know anything about the child control so it cannot easily cause code to execute in the child control's object.

H.B.
  • 166,899
  • 29
  • 327
  • 400
Locksleyu
  • 5,192
  • 8
  • 52
  • 77

2 Answers2

0

I'm not sure if I understood what you want to achieve, but if the problem is in getting one more callback/event to track changes on dependency property(or attached property) then this:

Attached Property Changed Event?

might be a solution.

Community
  • 1
  • 1
kubal5003
  • 7,186
  • 8
  • 52
  • 90
0

If you're using MVVM, keep in mind that your application should be your ViewModels, not your Views

With that being said, the Mode property should be on a ViewModel somewhere, and if the PropertyChange code isn't related to the UI, than it should be located in your ViewModel as well.

For example, I might have

while the ViewModel might look like this:

public class MyViewModel : INotifyPropertyChanged
{
    public MyViewModel()
    {
        this.PropertyChanged += MyViewModel_PropertyChanged;
    }

    void MyViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "Mode")
        {
            // Perform some logic here
        }
    }

    private int _mode;
    public int Mode
    {
        get { return _mode; }
        set
        {
            if (value != _mode)
            {
                _mode = value;
                RaisePropertyChanged("Mode");
            }
        }
    }
}
Rachel
  • 130,264
  • 66
  • 304
  • 490
  • Right now I have the Mode property stored in the child control since it is UI-related. I was able to use the DependencyPropertyDescriptor.AddValueChanged() API to solve my problem in a pretty clean way. – Locksleyu Oct 20 '11 at 14:49