从绑定列表视图 WPF C# 中的上下文菜单中获取项目

getting items from context menu in binding listview WPF c#

我是 Microsoft 的新手 visual studio WPF C# .. 我编写的代码显示用于绑定列表视图的上下文菜单,当我们右键单击列表中的项目时,它将删除它...... 我想在删除之前获取项目的价值

**xaml

<ListView Name="listview1" HorizontalAlignment="Left" Height="350" Margin="251,63,0,0" VerticalAlignment="Top" Width="214" FontSize="16" FontWeight="Bold">
        <ListView.ContextMenu>
            <ContextMenu>
                <MenuItem Header="Remove"
                Click="MenuItemDelete_Click" 
        Command="{Binding RemoveItem}"
        CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.SelectedItem}" />
            </ContextMenu>

        </ListView.ContextMenu>
        <ListView.View>
            <GridView>
                <GridView.Columns>

                    <GridViewColumn x:Name="Dtime" DisplayMemberBinding=
                      "{Binding Path=Dtime}" 
                  Header=" Date" Width="120"/>
                    <GridViewColumn x:Name="Patient"  DisplayMemberBinding=
                      "{Binding Path=Patient}"   
                  Header="Patient" Width="80"/>
                </GridView.Columns>
            </GridView>
        </ListView.View>

**代码

 class myresult {

        public String Dtime{ get; set; }
        public String Patient{ get; set; }

    }




 private void MenuItemDelete_Click(object sender, RoutedEventArgs e)
    {

            if (listview1.SelectedIndex == -1)
            {
                return;
            }

// here I will get the Item I want but I cant get the value inside the item                 

       var asw = listview1.Items.GetItemAt(listview1.SelectedIndex);



        listview1.Items.RemoveAt(listview1.SelectedIndex);
    }

您可以获取 SelectedItemDataContext 并将其转换为 myresult 对象。

myresult result = ((FrameworkElement)listview1.SelectedItem).DataContext as myresult;

或者,您可以使用与之前相同的 SelectedIndex 方法。

myresult result = ((FrameworkElement)asw).DataContext as myresult;