Search code examples
c#wpfevents

Unable to handle MouseDown event from ListView Item (Label)


I have a List View which I am populating with Labels via code. When the user clicks the label I want to handle the MouseDown event, but it doesn't fire. The preview mouse down does fire.

I understand there is something here about routing / bubbling events which I guess is going to the issue I'm hitting, this is a concept I'm yet to grasp.

I cannot use the preview event as this does not contain the object I need (the label information does not get assigned until the second click of the label, so I assume I need the MouseDown and not the preview)

Appreciate your time.

XAML

 <telerik:RadTabItem x:Name="Media" Header="Media" Height="22" Width="100">
                <Grid x:Name="ListboxMedia">


                    <ListView x:Name="ListViewImages" HorizontalAlignment="Left" Height="303" Margin="697,10,0,0" VerticalAlignment="Top" Width="178" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto" IsTabStop="True" TabIndex="3" MouseDown="ListViewImages_MouseDown" PreviewMouseDown="ListViewImages_PreviewMouseDown">
                        <ListView.View>
                            <GridView>
                                <GridViewColumn x:Name="ListViewImageColumn" Header="Images" Width="178" />
                            </GridView>
                        </ListView.View>
                    </ListView>

                    <Button x:Name="BtnUpload" Content="Upload" Height="24" Margin="809,318,38,0" VerticalAlignment="Top" Click="BtnUpload_Click"/>
                    <Button x:Name="BtnDownload" Content="Download" Height="24" Margin="728,318,109,0" VerticalAlignment="Top"/>
                    <Image x:Name="ImageViewPort" HorizontalAlignment="Left" Height="293" Margin="21,20,0,0" VerticalAlignment="Top" Width="581"/>
                </Grid>

            </telerik:RadTabItem>

Method which populates Labels into ListViewImages

 void PopulateMedia()
        {
            var collectImages = new Media().CollectMediaForAsset(_assetId);

            int i = 1;

            foreach (var collectImage in collectImages)
            {
                var label = new Label();
                label.Tag = collectImage.FileName;
                label.Content = "Image" + i.ToString();
                ListViewImages.Items.Add(label);                
                i++;
            }
        }

Handlers

 private void ListViewImages_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            Debug.WriteLine("Clicked Down"); //does not work


        }

        private void ListViewImages_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            Debug.WriteLine("Clicked Preview"); //works


        }

Solution

  • Used selection changed event instead