3

I have a ListBox with binding, when i add Items it works perfect but if i try to remove the items with contextMenu it doesnt work.

Here is what i try so far ListBox Xaml Code

   <ListBox Name="lstPersons"
                     VerticalAlignment="Stretch"
                     HorizontalAlignment="Stretch" Margin="126,-228,2,-242">
                <toolkit:ContextMenuService.ContextMenu>
                    <toolkit:ContextMenu Name="PersonContext">
                        <toolkit:MenuItem Name="PersonDelete" Header="Delete" Click="DeletePerson_Click"/>
                    </toolkit:ContextMenu>
                </toolkit:ContextMenuService.ContextMenu>
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel>    
                            <TextBlock Name="btnKellnerName"                                      
                                             Text="{Binding _PersonName}" 
                                             FontSize="35" 
                                             FontFamily="Portable User Interface"/>
                            <TextBlock Name="btnPosition"
                                             Text="{Binding _PersonPosition}"
                                             FontSize="22"/>
                            <TextBlock Name="lblUhrzeit" 
                                             Text="{Binding _CreationDate}"
                                             FontSize="18"/>
                            <TextBlock Name="Space" Text="                "/>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

And the Binding Class Code

public class Person 
{    
    public string _PersonName { get; set; }      
    public string _PersonPosition { get; set; }    
    public string _CreationDate { get; set; }   
}

When i add items like this

ObservableCollection<Person> personList = new ObservableCollection<Person>();

personList.Add(new Person { 
_PersonName = "Tom",
_PersonPosition = "Bla", 
_CreationDate = "33"
});

this.lstPerson.ItemSource = personList;

it works pefect! Now i Want to remove a selected Item with the ContextMenu like this

private void DeletePerson_Click(object sender, RoutedEventArgs e)
{   
   int indexPerson = lstPerson.SelectedIndex;

   personList.RemoveAt(indexPerson);
}    

but it doesnt work. Does Anybody have an Idea what im making wrong? Thanks

Ok Guys i have now the Solution the Problem was the value of SelectedIndex now ive got the right Value. First ive put the ContextMenu inside ListBoxItemTemplate/StackPanel

Code Behind:

private void DeletePerson_Click(object sender, RoutedEventArgs e)
  {
      try {

                var selectedListBoxItem = listBox.ItemContainerGenerator.ContainerFromItem(((MenuItem) sender).DataContext) as ListBoxItem;
                var selectedIndex = listBox.ItemContainerGenerator.IndexFromContainer(selectedListBoxItem);

                _personList.RemoveAt(selectedIndex);
         }
         catch( Exception ex ) { MessageBox.Show(ex.Message); };
  }    
iNCEPTION
  • 45
  • 1
  • 7
  • does it work if you add the item(s) before assigning `personList` to `ItemsSource`? If not, there is a binding problem. Also, is that a typo - should be `ItemsSource` not `ItemSource`. – RobSiklos Aug 30 '13 at 13:25
  • Doesn't work in what way? Exception, or no exception and item remains in list? – weston Aug 30 '13 at 13:32
  • Thanks guys for the Answers. I have debugged it and there Is a Problem wit listBox.SelectedIndex the value is -1. So the ContextMenu is not at the right place because i do not get the selected Index – iNCEPTION Aug 30 '13 at 13:44

4 Answers4

0

Try to add this when the form is initialized:

lstPersons.ItemsSource = personList ;

How to: Create and Bind to an ObservableCollection

It appears that the problem is due to selected item

The key is setting the PreviewMouseRightButtonDown event in the correct place. As you'll notice, even without a ContextMenu right clicking on a ListViewItem will select that item, and so we need to set the event on each item, not on the ListView.

<ListView>
    <ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListViewItem}">
            <EventSetter Event="PreviewMouseRightButtonDown"
                         Handler="OnListViewItemPreviewMouseRightButtonDown" />
        </Style>
    </ListView.ItemContainerStyle>
    <ListView.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Menu Item">Item 1</MenuItem>
            <MenuItem Header="Menu Item">Item 2</MenuItem>
        </ContextMenu>
    </ListView.ContextMenu>
    <ListViewItem>Item</ListViewItem>
    <ListViewItem>Item</ListViewItem>
    <ListViewItem>Item</ListViewItem>
    <ListViewItem>Item</ListViewItem>
    <ListViewItem>Item</ListViewItem>
    <ListViewItem>Item</ListViewItem>
</ListView>

.

private void OnListViewItemPreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    Trace.WriteLine("Preview MouseRightButtonDown");

    e.Handled = true;
}

wpf listview right-click problem

Community
  • 1
  • 1
Joan Caron
  • 1,969
  • 18
  • 21
0

In addition to what Joan said, you can also do this in Xaml like this:

<ListBox ItemsSource={Binding personList}
                 VerticalAlignment="Stretch"
                 HorizontalAlignment="Stretch" Margin="126,-228,2,-242">
            <toolkit:ContextMenuService.ContextMenu>

</ListBox>

You should read how to use Bindings and the MVVM-Model. It's pretty convenient for stuff like this. Here are some links: http://channel9.msdn.com/Events/MIX/MIX10/EX14 http://channel9.msdn.com/Events/MIX/MIX11/OPN03

Don't get discouraged. It's a bit of learning at the beginning, but it's totally worth it. I also had some problems with displaying lists, before I started doing everything with MVVM using Laurent Bugnions' MvvmLight package.

Florian Baierl
  • 2,378
  • 3
  • 25
  • 50
0

try this:

private void DeletePerson_Click(object sender, RoutedEventArgs e)
    {   
       System.Collections.IList pathRemove;
       pathRemove = lstPerson.SelectedItems;

       if(pathRemove.Count != 0)
          {
               for (int i = pathRemove.Count - 1; i >= 0; i--)
                    {
                        lstPerson.Remove((Person)pathRemove[i]);//multiple deletes
                    } 
         }


    } 
Naresh
  • 633
  • 1
  • 7
  • 26
  • Thanks for the Answers. I have debugged it and there Is a Problem wit listBox.SelectedIndex the value is -1. So the ContextMenu is not at the right place because i do not get the selected Index – iNCEPTION Aug 30 '13 at 13:45
0

Why don't use binding for all.

Bind item source as ObservableCollection blabla

Bind Selecteditem as XXXX

Use command for your button and when you want remove an item do :

blabla.remove(SelectedItem);
MatDev8
  • 976
  • 5
  • 18