2017-08-17 62 views
0

我有一个ItemTemplate一个ListBox所以每个项目显示了其在TextBlockNameButton删除这个项目。与项目内的按钮来删除一个ListBoxItem而不选择项

我可以删除该项目,当我选择该项目,然后单击“删除”按钮。但我不想选择该项目,只需单击删除按钮并删除包含删除按钮的当前项目。

我在上面添加了一些我的代码。我怎样才能做到这一点?

XAML代码

<ListBox Grid.Row="1" x:Name="listBoxProduct" SelectionMode="Single" Margin="0" Background="Transparent" ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.HorizontalScrollBarVisibility="Hidden" Height="200"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <Border BorderThickness="1" Margin="0" Height="45" CornerRadius="4" Width="875" Background="#2E323B" BorderBrush="Black"> 
       <DockPanel> 
        <TextBlock Text="{Binding Customer}" Foreground="White" TextWrapping="Wrap" FontSize="16" HorizontalAlignment="Left" Margin="70,0,0,0" Width="230" VerticalAlignment="Stretch"/> 
        <TextBlock Text="{Binding Piece}" Foreground="White" TextWrapping="Wrap" FontSize="16" HorizontalAlignment="Left" Margin="4,0,0,0" Width="200" VerticalAlignment="Center"/> 
        <TextBlock Text="{Binding Material}" Foreground="White" TextWrapping="Wrap" FontSize="16" HorizontalAlignment="Left" Margin="10,0,0,0" Width="100" VerticalAlignment="Center"/> 
        <TextBlock Text="{Binding Quantity}" Foreground="White" FontSize="16" HorizontalAlignment="Left" Margin="10,0,0,0" Width="50" VerticalAlignment="Center"/> 
        <TextBlock Text="{Binding Weight}" Foreground="White" FontSize="16" HorizontalAlignment="Left" Margin="40,0,0,0" Width="50" VerticalAlignment="Center"/> 
        <Button Content="Delete" Name="btnDelete" Foreground="Black" Background="#CCCCCC" HorizontalAlignment="Stretch" Margin="20,0,0,0" Height="35" Width="76" VerticalAlignment="Center" Click="btnDelete_Click"/> 
       </DockPanel> 
      </Border> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

C#代码

public partial class CreateProduct : Window 
{ 
    private ObservableCollection<Liste> list = new ObservableCollection<Liste>(); 

    private void btnDelete_Click(object sender, RoutedEventArgs e) 
    { 
     list.Remove((Liste)listBoxProduct.SelectedItem); 

    } 
} 

回答

1

试试这个:

private void btnDelete_Click(object sender, RoutedEventArgs e) 
{ 
    Button btn = sender as Button; 
    list.Remove((Liste)btn.DataContext); 
} 
+0

谢谢mm8.It做工精良。 – Barsblue

相关问题