简体   繁体   English

带有ListBoxItem的上下文菜单

[英]Context menu with ListBoxItem

I am using a ContextMenu in my xaml page under a ListBox to delete the ListBox Item.The problem I am facing is that when I long press the ListBoxItem the delete option appears and the item is deleted but when I try the next time the other item is not deleted.So can anyone tell me how on click of ContextMenu.Menuitem I can retrieve the list box Item details.Here's my code. 我在xaml页面的ListBox下使用ContextMenu删除ListBox Item。我面临的问题是,当我长按ListBoxItem时,出现delete选项并删除该项目,但是当我下次尝试其他项目时没有被删除。所以谁能告诉我如何单击ContextMenu.Menuitem我可以检索列表框Item的详细信息。这是我的代码。

private void deleteitem_Click(object sender, RoutedEventArgs e)
    {
        NavigationContext.QueryString.TryGetValue("username", out username);
        NavigationContext.QueryString.TryGetValue("password", out password);
        ListBoxItem selecteditem = this.sniplist.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
        Item item = selecteditem.DataContext as Item;
        HttpWebRequest deleterequest = (HttpWebRequest)WebRequest.Create(url);
        HttpWebResponse response=deleterequest.BeginGetResponse(new AsyncCallback(deleteitem),deleterequest) as HttpWebResponse;
        //MessageBox.Show("Your item has been deleted");
    }

The deleteitem method deleteitem方法

private void deleteitem(IAsyncResult ar)
{
//throw new NotImplementedException();
HttpWebRequest request=(HttpWebRequest)ar.AsyncState;
HttpWebResponse response=(HttpWebResponse)request.EndGetResponse(ar);
if(response.StatusCode==HttpStatusCode.OK)
{
    using(Stream respstream=response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(respstream,
 System.Text.Encoding.UTF8);
                string parsestring = reader.ReadToEnd();
                Debug.WriteLine("Response data:" + parsestring);
            }
}
Deployment.Current.Dispatcher.BeginInvoke(() =>
    {
        items.Remove(item1);
        this.sniplist.ItemsSource = items;
        MessageBox.Show("You item has been deleted");
        if (sniplist.Items.Count == 0)
        {
            txt1.Text = "Please click + to add more items into your account";
        }
    });


     }
   }
 }

Please help, I am stuck on this since two days. 请帮忙,我已经两天了。

I solve the problem by using the following 我通过使用以下解决问题

var item = ((MenuItem)sender).DataContext as ItemClass

ItemClass is the class that contains the binding details of different items, ItemClass是包含不同项目的绑定详细信息的类,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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