views:

34

answers:

2

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" 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>

The code is from a silverlight 4 project. Thanks.

+1  A: 
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.

HCL
This worked, i resolved the problem.Thank you HCL.
tribanp
A: 

Hi

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

Daniel
With the id the problem was that i could have multiple id with the same number.But thanks.
tribanp