Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listening for changes to IsEnabled on a Wpf Element

I want to listen for changes to the IsEnabled property on WPF elements (so that I can run some common code whenever it changes) without having to put a load of code in each window/page.

I also want to avoid any potential problems with memory leaks due to strong event listeners. I've come across some articles that suggest using weak event listeners etc. but that seems awfully complicated for something that seems like it should be really easy.

I don't want to have to subclass controls in order to do this as there are several control types (and probably more in future) that I want to listen for the IsEnabled change on.

Has anyone come up with a neater way of handling this?

like image 818
fubaar Avatar asked Aug 04 '11 11:08

fubaar


2 Answers

A neat solution to this problem would to create a custom attached property and setup a one way binding with the IsEnabled property as the source:

<Control IsEnabled={Binding IsEnabledProperty}
         AttachedProperty={Binding RelativeSource={RelativeSource Self}, Path=IsEnabled, Mode=OneWay}"/>

This allows you to handle the common functionality in the attached property's changed handler (which could involve firing a custom routed event as IsEnabled is a regular CLR event and won't bubble up).

like image 200
user878471 Avatar answered Nov 03 '22 21:11

user878471


There is a Control.IsEnabledChanged event.

like image 5
Andreas Avatar answered Nov 03 '22 23:11

Andreas