How to remove a custom item from a listBox and ObservableCollection when click on a button
I have the listBox and a ObservableCollection. The listBox.ItemSource (listNotify.ItemSource) is set to that ObservableCollection (errosList). The problem that i have is that i don`t know how to remove the correct element from errorsList when the user click on the button with content x from listBox. For the item of the listBox i use a ItemTemplate, inside a stackPanel and in stackPanel i have a button. Bellow is the XAML code:
<ListBox x:Name="listNotify">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="35">
<Image Height="16" Source="/Template;component/Resources/error.png" Stretch="Fill" Ver开发者_如何学CticalAlignment="Top" Width="16"/>
<StackPanel Orientation="Vertical">
<HyperlinkButton Content="{Binding ErrorHeader}" HorizontalAlignment="Left" Height="16" Width="125"/>
<TextBlock Text="{Binding ErrorMessage}" HorizontalAlignment="Left" Width="405" d:LayoutOverrides="VerticalAlignment" />
</StackPanel>
<Button Content="x" Width="20" Height="20" Click="removeError_Click"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The code is from a silverlight 4 project. Thanks.
private void removeError_Click(object sender, RoutedEventArgs e) {
FrameworkElement fe = sender as FrameworkElement;
if (null != fe) {
_observableCollection.Remove((YourType)fe.DataContext);
}
}
Should do what your looking for. Replace YourType with the type you declared in the ObservableCollectiion.
Don't you have an ID-like property in your Items of the errorsList-Collection? Then you could use the Tag-Property of the Button to archieve this:
<Button Content="x" Width="20" Height="20" Tag="{Binding ID}" Click="Button_Click" />
and in the click-event of the button:
string id = ((Button) sender).Tag.ToString();
var itemToRemove = errorsList.Where(x => x.ID == id).First();
errorsList.Remove(itemToRemove);
Hope that helps
精彩评论