2010-08-07 33 views
3

我有listBox和ObservableCollection。 listBox.ItemSource(listNotify.ItemSource)被设置为该ObservableCollection(errosList)。 我的问题是,我不知道如何从错误列表中删除正确的元素,当用户点击列表框中的内容x的按钮。对于listBox的项目,我使用ItemTemplate,在一个stackPanel和一个stackPanel中,我有一个按钮。 娄是XAML代码:如何从列表框和ObservableCollection中删除自定义项,点击按钮

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

的代码是从一个Silverlight 4项目。 谢谢。

回答

1
private void removeError_Click(object sender, RoutedEventArgs e) { 
    FrameworkElement fe = sender as FrameworkElement; 
    if (null != fe) { 
     _observableCollection.Remove((YourType)fe.DataContext); 

    } 
} 

应该做你想要的。将YourType替换为您在ObservableCollectiion中声明的类型。

+0

这个工作,我决心问题。 谢谢HCL。 – tribanp 2010-08-07 09:25:53

0

在你的errorsList-Collection项目中你没有类似ID的属性吗?然后,你可以用按钮的标签属性来archieve此:

<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

与id的问题是,我可以有多个id与相同的号码。 但是,谢谢。 – tribanp 2010-08-07 09:26:37

相关问题