0
<Window.Resources>
    <DataTemplate x:Key="myTaskTemplate">
        <ListViewItem MouseDown="ListviewItemClicked"></ListViewItem>
    </DataTemplate>
</Window.Resources>
<Grid>
    <ListView x:Name="Mijnlijst" Margin="43,61,48,24" ItemTemplate="{StaticResource myTaskTemplate}">
        <ListView.View>
            <GridView>
                <GridViewColumn/>
            </GridView>
        </ListView.View>
    </ListView>
    <TextBox HorizontalAlignment="Left" Height="23" Margin="43,21,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="353"/>
    <Button Content="Button" HorizontalAlignment="Left" Height="34" Margin="530,10,0,0" VerticalAlignment="Top" Width="123" Click="Button_Click"/>
</Grid>

c#:

    public partial class MainWindow : Window
{
    string[] mydata = new string[] { "a", "b", "c" };
    public MainWindow()
    {
        InitializeComponent();
        
    }

    private void hyperlink_clicked(object sender, RoutedEventArgs e)
    {
        //Hyperlink hl = (Hyperlink)sender;
        //ProcessStartInfo psi = new ProcessStartInfo(hl.NavigateUri.ToString());
        //Process.Start(psi);
        MessageBox.Show(mydata.ToString());
        
    }

    private void ListviewItemClicked(object sender, MouseButtonEventArgs e)
    {
        ListViewItem lv = (ListViewItem)sender;
        MessageBox.Show(lv.Content.ToString());
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Mijnlijst.ItemsSource = mydata;
        Mijnlijst.AddHandler(ListViewItem.PreviewMouseDownEvent, new MouseButtonEventHandler(ListviewItemClicked));
    }
}

I want to add a PreviewMouseDown event to the listview-elements in the listview. In example given; the event is called when there is a mousedownevent on the listview; not knowing which listviewitem in particular is clicked. The event is also triggered when the listview but no element is clicked. That's why I get an exception when casting (ListViewItem)sender.

So how to add or route events that are triggered by the elements in particular?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Jomme
  • 1,256
  • 4
  • 14
  • 26

0 Answers0