Listening for changes to IsEnabled on a Wpf Element
Asked Answered
I

2

6

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?

Inoperative answered 4/8, 2011 at 11:29 Comment(0)
H
5

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).

Harry answered 4/8, 2011 at 11:41 Comment(0)
P
6

There is a Control.IsEnabledChanged event.

Pitchblende answered 28/1, 2013 at 13:21 Comment(1)
Actually, it is named IsEnabledChanged.Snide
H
5

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).

Harry answered 4/8, 2011 at 11:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.