简体   繁体   中英

Correct way to check for property change in design mode C# WPF?

Ok, so I'm trying to run some code that modifies a UI when a user changes a custom control's dependency property value in design mode; but only when in design mode.

I've tried these approaches:

1.
public static DependencyProperty x = ...Register(..., new PropertyMetadata(null, changeMethod));

2.
set { SetValue(XProp, value); changeMethod(value); }

3.
var observable = x as INotifyPropertyChanged;
observable.PropertyChanged += ObservablePropertyChanged;

But all of them seem to have their own issues in that they either trigger errors or don't work at all.

So does anyone know what the correct way to listen to a dependency property change in design mode is, and if so can you give an example?

The right way to handle DependencyProperty changes is to:

. Declare the DependencyProperty:

public static DependencyProperty MyXProperty;

. Create the public get/set Property:

public string MyX
{
    get { return (string)GetValue(MyXProperty); } //Supposing that the property type is string
    set { SetValue(MyXProperty, value); }
}

. Register the DependencyProperty in your static constructor:

static MyClass()
{
    MyXProperty= DependencyProperty.Register("MyX", typeof(string), typeof(MyClass), new FrameworkPropertyMetadata("", OnMyXPropertyChanged));
}

. Declare the Property Changed Method:

private static void OnMyXPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
{
    MyClass thisClass = d as MyClass ;
    //Do Something            
}

Please provide more information if you still can't find your solution.

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