Reputation: 23
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);
}
Upvotes: 1
Views: 1070
Reputation: 9713
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;
Upvotes: 1