Search code examples
wpfexpanderrouted-events

How do I swallow the dropdown behavior inside an Expander.Header?


I would like to prevent an Expander from expanding/collapsing when users click inside the header area. This is basically the same question as Q 1396153, but I'd appreciate a more favorable answer :)

Is there a non-invasive way to do this? I am not sure exactly how to attach behavior to the Expander.Header content to prevent mouseclicks. I'm willing to float in content outside the expander itself via a fixed grid layout, but I'm not keen on the solution. Ideas?

XamlPad sample XAML:

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
    <Expander>
    <Expander.Header><TextBlock>
        When I click this text, 
        I don't want to trigger expansion/collapse! Only when I click the 
        expander button do I want to trigger an expand/collapse!
    </TextBlock></Expander.Header>

    <Grid Background="Red" Height="100" Width="100" >
    </Grid>
    </Expander>
</Page>

Solution

  • You can stop mouse clicks on the text box from being handled by your application.

    XAML:

    <Expander>
        <Expander.Header>
            <TextBlock MouseDown="TextBlock_MouseDown"> 
                When I click this text,  
                I don't want to trigger expansion/collapse! Only when I click the  
                expander button do I want to trigger an expand/collapse!
                        </TextBlock>
            </Expander.Header>
        <Grid Background="Red" Height="100" Width="100" >
        </Grid>
    </Expander>
    

    Code behind:

    private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
    {
        e.Handled = true;
    }