[英]How to remove a custom item from a listBox and ObservableCollection when click on a button
I have the listBox and a ObservableCollection. 我有listBox和ObservableCollection。 The listBox.ItemSource (listNotify.ItemSource) is set to that ObservableCollection (errosList).
listBox.ItemSource(listNotify.ItemSource)设置为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.
我遇到的问题是当用户点击带有来自listBox的内容x的按钮时,我不知道如何从errorsList中删除正确的元素。 For the item of the listBox i use a ItemTemplate, inside a stackPanel and in stackPanel i have a button.
对于listBox的项目,我在stackPanel中使用ItemTemplate,在stackPanel中我有一个按钮。 Bellow is the XAML code:
Bellow是XAML代码:
<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. 代码来自silverlight 4项目。 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.
将YourType替换为您在ObservableCollectiion中声明的类型。
Don't you have an ID-like property in your Items of the errorsList-Collection? 你在errorsList-Collection的Items中没有类似ID的属性吗? Then you could use the Tag-Property of the Button to archieve this:
然后你可以使用Button的Tag-Property来实现这个目的:
<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 希望有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.