2017-08-17 35 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

相關問題