使用ContextMenu获取ListBox的选定项

时间:2016-06-20 16:20:45

标签: wpf listbox contextmenu

我正在研究WPF。我有ListBox,我通过“ObservableCollection”以编程方式添加ListBox项,因为我必须在运行时添加和删除。我在ListBoxItems上有ContextMenu。现在我想通过单击上下文菜单来获取所选项目。这是我的代码:

的.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
    }

和.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>

这是截图。

enter image description here

当我右键点击Gopi并点击开始时我想在MenuItemStart_Click中找到“Gopi”

现在我应该在“MenuItemStart_Click”事件中写什么来获取所选项目。我尝试了e.OriginalSource as MenuItemsender as MenuItem,但没有用。任何人都可以帮我解决这个问题。提前致谢

1 个答案:

答案 0 :(得分:0)

为什么不绑定所选的项目属性呢?

A ~ Double

然后在您的可观察集合旁边的代码中

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