David Hollinshead
David Hollinshead

Reputation: 1790

Collapse an Expander when it is disabled

I have an Expander that I want the user to be able to expand/collapse. However I want to collapse the Expander when IsEnabled is set false.

This works:

myExpander.IsEnabledChanged += (sender, e) => 
{ 
  if (!((Expander)sender).IsEnabled) ((Expander)sender).IsExpanded = false; 
};

but I was hoping for a cleaner solution with maybe a Style or a Binding.

I tried:

<Style x:Key="NotesExpander" TargetType="Expander" >
    <Setter Property="IsExpanded" Value="True" />
    <Style.Triggers>
        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="IsExpanded" Value="False" />
        </Trigger>
    </Style.Triggers>
</Style>

which works until the user sets IsExpanded interactively. At soon as the user clicks to expand manually the style no longer provides the value for IsExpanded.

Any suggestions?

Regards David

Upvotes: 1

Views: 361

Answers (1)

larsbw
larsbw

Reputation: 61

this is an issue of dependency property setting precedence (read e.g. link1 and link 2). Once IsExpanded has been changed interactively by the user, this value has higher precedence than your style trigger.

One possible solution would be something along these lines...

Add PreviewMouseDown="exp_PreviewMouseDown" to your Expander. In this event handler use DependencyObject.SetCurrentValue to update the value, instead of letting the Expander update the value itself (which would override your style trigger):

private void exp_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    var exp = sender as Expander;
    exp.SetCurrentValue(Expander.IsExpandedProperty, !exp.IsExpanded);
    e.Handled = true;
}

Upvotes: 4

Related Questions