I am working on WPF. I have ListBox and I am adding ListBox Items programatically through "ObservableCollection" as I have to add and remove at runtime. I am having ContextMenu on ListBoxItems. Now I want to get the selected item by clicking on the contextmenu. Here is my code:
.cs
ObservableCollection<string> MyItems = null;
public MessageTrcr()
{
InitializeComponent();
MyItems = new ObservableCollection<string>();
listofConnectedItems.ItemsSource = MyItems;
CreateListItem("Sandeep");
CreateListItem("Gopi");
}
public void CreateListItem(String ItemName)
{
MyItems.Add(ItemName);
}
private void MenuItemStart_Click(object sender, RoutedEventArgs e)
{
// What should I write here to get selected Item
}
and .xaml
<Grid>
<ListBox x:Name="listofConnectedItems" Grid.Column="0" Grid.Row="0" ItemsSource="{Binding MyItems}" >
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Padding" Value="10">
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ContextMenu>
<ContextMenu x:Name="contextMenu">
<MenuItem Header="_Start" Click="MenuItemStart_Click" />
<MenuItem Header="Sto_p" />
<MenuItem Header="_Clear" />
</ContextMenu>
</ListBox.ContextMenu>
</ListBox>
</Grid>
Here is the screenshot.
When I right click on Gopi and click on Start I want "Gopi" in MenuItemStart_Click
Now what should I write in "MenuItemStart_Click" event to get the selected Item. I tried e.OriginalSource as MenuItem
and sender as MenuItem
but of no use. Can any one please get me through this. Thanks in advance