i have made a listbox datatemplated with button and binded to a textbox. i would like to be able removing one item by a tap & hold. my probleme : an invalid operation exception pops
here is my code
Button remover = (Button)sender;
fileListbox.Items.Remove(remover.Content);
System.InvalidOperationException was unhandled
Message=Operation not supported on read-only collection.
StackTrace:
à System.Windows.Controls.ItemCollection.RemoveImpl(Object value)
à System.Windows.Controls.ItemCollection.RemoveInternal(Object value)
à System.Windows.PresentationFrameworkCollection1.Remove(Object value)
à proByOrange.views.preDevis.Page1.GestureListener_Tap(Object sender, GestureEventArgs e)
à Microsoft.Phone.Controls.SafeRaise.Raise[T](EventHandler
1 eventToRaise, Object sender, GetEventArgs1 getEventArgs)
à Microsoft.Phone.Controls.GestureListener.RaiseGestureEvent[T]开发者_如何学Python(Func
2 eventGetter, Func`1 argsGetter, Boolean releaseMouseCapture)
à Microsoft.Phone.Controls.GestureListener.ProcessTouchPanelEvents()
à Microsoft.Phone.Controls.GestureListener.TouchComplete()
à Microsoft.Phone.Controls.GestureListener.Touch_FrameReported(Object sender, TouchFrameEventArgs e)
à System.Windows.Input.Touch.OnTouch(Object sender, TouchFrameEventArgs e)
à MS.Internal.JoltHelper.RaiseEvent(IntPtr target, UInt32 eventId, IntPtr coreEventArgs, UInt32 eventArgsTypeIndex)
thx for help
You're trying to remove an item from a ReadOnly collection. You can't change such a collection. As you may expect by the name you can only read such a collection, you can't change it.
You're title refers to a textbox but your code and stacktrace imply something using an ItemsSource.
If you need to be able to change what is displayed, just make the UI elements readonly and leave the backing collections writeable.
If you can show some example code we can show how to change it appropriately.
If you've bound the ListBox
to a list somewhere (in a view model would be good) by using the ItemsSource
property as Matt suggests and your question implies, then in order to remove an item from the list, remove it from the source collection. The best approach if you are modifying the contents of the list is to use ObservableCollection<T>
, which raises collection changed notification when the collection changes, so your UI will update automatically:
public ObservableCollection MyList { get; private set; }
...
// Inside an event handler or view model command handler.
this.MyList.Remove(itemToRemove);
精彩评论