Software & Finance





WPF ListBox - Adding Events at runtime





Adding events at runtime for the listboxitem is an easy job. Get the listbox item and then assign the eventhandler. I have added MouseDoubleClick event on this sample.

Here is the XAML code:

<Button Name="Event" Content="Event" Click="AddEvent_Click" Width="40" Height="24" Margin="10,0,0,0" HorizontalAlignment="Center"  VerticalAlignment="Center"></Button>

 

<ListBox Grid.Row="2" Name="gui_studentListBox"  Width="240" Height="176" Margin="15,22,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" Visibility="Visible" SelectionMode="Single" ItemsSource="{Binding}"/>

 

 

Here is the .cs code:

 

private void AddEvent_Click(object sender, RoutedEventArgs e)

{

    for (int i = 0; i < gui_studentListBox.Items.Count; i++)

    {

ListBoxItem lbi = (ListBoxItem) gui_studentListBox.ItemContainerGenerator.ContainerFromItem(gui_studentListBox.Items[i]);

      lbi.MouseDoubleClick += new MouseButtonEventHandler(lbi_MouseDoubleClick);

     }

}

void lbi_MouseDoubleClick(object sender, MouseButtonEventArgs e)

{

     throw new NotImplementedException();

}