Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a click event from a GridViewColumn header?

Tags:

c#

wpf

I can get events from everything under the headers, but I can't get an event from clicking the headers. Here's the XAML; notice the event is for the entire ListView, so it should activate when anything is clicked:

<ListView x:Name="myListView" MouseLeftButtonUp="myListView_MouseLeftButtonUp" Margin="10">
    <ListView.View>
        <GridView>
            <GridView.Columns>
                <GridViewColumn Header="File Path"
                                DisplayMemberBinding="{Binding Path=Path}"  />
                <GridViewColumn Header="File Size"
                                DisplayMemberBinding="{Binding Path=Size}" />
            </GridView.Columns>
        </GridView>
    </ListView.View>
</ListView>

And the event itself is very simple. Just show me that something has happened:

    private void myListView_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        string output = sender.ToString();
        MessageBox.Show(output);
    } 

Clicking anywhere under the headers responds perfectly:
"System.Windows.Controls.ListView Items.Count:0"

Clicking the "File Path" header does nothing. Clicking the "File Size" header does nothing.

MSDN says:
https://msdn.microsoft.com/en-us/library/vstudio/ms745786(v=vs.100).aspx

<ListView x:Name='lv' Height="150" HorizontalAlignment="Center" VerticalAlignment="Center" 
GridViewColumnHeader.Click="GridViewColumnHeaderClickedHandler">

Visual Studio says there's no such thing as GridViewColumnHeader, so none of the code on MSDN works.

like image 539
Shawn Darichuk Avatar asked Oct 20 '22 06:10

Shawn Darichuk


1 Answers

That's how WPF UI events work by default. They bubble up. If somebody eats the message along the way (which is what button type controls do), the higher level controls won't get it. You can either use the Preview version of the event, or the cleaner way to do it:

AddHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(ListView_OnColumnClick));
like image 173
SledgeHammer Avatar answered Oct 21 '22 23:10

SledgeHammer