2016-06-20 6 views
1

WPF에서 작업 중입니다. 나는 ListBox를 가지고 있으며 런타임에 추가하고 제거해야하는 "ObservableCollection"을 통해 ListBox Items를 프로그래밍 방식으로 추가하고 있습니다. ListBoxItems에 ContextMenu가 있습니다. 이제 컨텍스트 메뉴를 클릭하여 선택한 항목을 가져 오려고합니다.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 : 여기 내 코드입니다. 내가 바로 Gopi 클릭하고 내가 선택한 항목을 얻을 "MenuItemStart_Click"이벤트로 작성해야하는지 이제 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

@ Gopi 이것이 올바른 방법임을 확신합니다. 배후 코드에서 이름을 통해 객체에 액세스하는 것은 유지 관리 할 수 ​​없습니다. MVVM 구조로 전환하면 어떻게됩니까? 어쨌든, 행운을 비네. –

관련 문제