私はWPFで作業しています。私はListBoxを持っており、私は追加して実行時に削除する必要があるので、 "ObservableCollection"を介してプログラム的にListBox Itemsを追加しています。私はContextMenuをListBoxItemsに持っています。ここで、コンテキストメニューをクリックして、選択したアイテムを取得します。ContextMenuを使用してListBoxの選択項目を取得
は.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
}
ここで
<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>
はスクリーンショットであるの.xaml:ここに私のコードです。私は右
MenuItemStart_Click
で「Gopiは」今、私が選択した項目を取得するには、「MenuItemStart_Click」イベントで何を書くべき私が欲しいGopiをクリックして、[開始]をクリックします
。私はe.OriginalSource as MenuItem
とsender as MenuItem
を試したが、役に立たなかった。誰もがこれを私を得ることができます。事前に感謝します
listofConnectedItems.SelectedItemか?それはあなたにそれを与えるべきである – adminSoftDK
@ adminSoftDKありがとう。それは完璧に働いた。私はそれを逃した方法を得ていない。とにかくあなたに感謝:) – Gopi