How to remove a custom item from the Box and ObservableCollection list when a button is clicked

I have a listBox and ObservableCollection. ListBox.ItemSource (listNotify.ItemSource) is set to this ObservableCollection (errosList). The problem that I have is that I do not know how to remove the correct item from errorsList when the user clicks the button with the contents of x from the Box list. For the listBox element, I use ItemTemplate, inside the stackPanel and in the 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" VerticalAlignment="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>

Code from silverlight 4 project. Thank you.

+3
source share
2 answers
private void removeError_Click(object sender, RoutedEventArgs e) {
    FrameworkElement fe = sender as FrameworkElement;
    if (null != fe) {
        _observableCollection.Remove((YourType)fe.DataContext);

    }
}

, . YourType , ObservableCollectiion.

+1

ID- ItemsList-Collection? Tag , :

<Button Content="x" Width="20" Height="20" Tag="{Binding ID}" Click="Button_Click" />

:

string id = ((Button) sender).Tag.ToString();
var itemToRemove = errorsList.Where(x => x.ID == id).First();
errorsList.Remove(itemToRemove);

,

0

Source: https://habr.com/ru/post/1758501/


All Articles