简体   繁体   中英

getting items from context menu in binding listview WPF c#

I'am new in Microsoft visual studio WPF C# .. I write code that show a context menu for binding listview and when we right click to the item in list it will remove it ... I want to get the value of the item before we remove it

**the 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>

**the code

 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);
    }

You can get the DataContext of the SelectedItem and cast it to a myresult object.

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

Alternatively, you can use the same SelectedIndex method you were using previously.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM