Timo Korinth

2 Meter, 2 Mark

Override IsEnabled dependency property

| 0 comments

Initial situation:

I’ve got a CustomControl (e.g. derived from ContentControl), which contains multiple other parts (let’s say a button).

Goal:

If I set “IsEnabled = false” on my CustomControl, only the content should be disabled, but not my button in the control template.

Problem:

The IsEnabled property will be inherited by the children of the visual tree and as a result, our button will be disabled too. Also there’s a IsEnabledChanged event, you cannot set the “IsHandled” property of the EventArgs to true with the expected result.

Solution:

There’s a little neat trick: As you can see in the following code snippet, you can override the IsEnabled dependency property in your CustomControl. The important part is the “new” keyword, both on the DependencyProperty registration and the property wrapper.

public new bool IsEnabled
{
    get { return (bool)GetValue(IsEnabledProperty); }
    set { SetValue(IsEnabledProperty, value); }
}

public static new readonly DependencyProperty IsEnabledProperty =
    DependencyProperty.register("IsEnabled", typeof(bool), typeof(FormItemControl),
    new PropertyMetadata(true, OnIsEnabledChanged));

public static void OnIsEnabledChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
    var control = sender as FormItemControl;
    if (control != null)
    {
        control.UpdateIsEnabled();
    }
}

public void UpdateIsEnabled()
{
    var content = Content as Control;
    if (content != null)
    {
        content.IsEnabled = IsEnabled;
    }
}

Leave a Reply