2016-06-20 13 views
1

私は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をクリックして、[開始]をクリックします

enter image description here

。私はe.OriginalSource as MenuItemsender as MenuItemを試したが、役に立たなかった。誰もがこれを私を得ることができます。事前に感謝します

+1

listofConnectedItems.SelectedItemか?それはあなたにそれを与えるべきである – adminSoftDK

+0

@ adminSoftDKありがとう。それは完璧に働いた。私はそれを逃した方法を得ていない。とにかくあなたに感謝:) – Gopi

答えて

0

なぜ選択された項目プロパティもバインドしませんか?あなたのコード内で次に

<ListBox 
    SelectedItem = {Binding SelectedItemProperty, Mode="TwoWay"} 
    x:Name="listofConnectedItems" 
    Grid.Column="0" Grid.Row="0" 
    ItemsSource="{Binding MyItems}" > 

次のあなたの監視可能なコレクション

public string SelectedItemProperty {get; set;} 
+0

私はあなたのコードをチェックしたが、何も表示されません。 @adminSoftDKは "listofConnectedItems.SelectedItem"が機能していると述べています。とにかくありがとう:) – Gopi

+0

@ゴピ私はこれが正しい方法であることを保証します。背後のコードで名前を使用してオブジェクトにアクセスすることは維持できません。 MVVM構造に切り替えるとどうなりますか?とにかく、それで幸運。 –

関連する問題