c# - 使用项目内的按钮删除 ListboxItem,而不选择项目

标签 c# wpf binding listbox itemtemplate

我有一个带有 ItemTemplateListBox,因此每个项目都会在 TextBlock 中显示其Name,并且用于删除此项的按钮

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

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

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

    }
}

最佳答案

试试这个:

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

关于c# - 使用项目内的按钮删除 ListboxItem,而不选择项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45737745/

相关文章:

jquery - 将 timeupdate 事件与 div 绑定(bind)

c# - 如何判断 .NET 中的反序列化 JSON 对象中是否曾经定义过某个键?

c# - 可编辑组合框为空时不更新

c# - 如何在 WPF C# 中更改 slider 上刻度的设计(刻度的厚度、刻度的形状等...)

WPF DataGrid RowHeader 数据绑定(bind)

c# - 了解 XAML/WPF 中的样式和模板

angularjs - 什么是 Angular 的双向数据绑定(bind)

c# - ML.NET 架构不匹配 : expected VarVector<Byte> got Vector<Byte>

c# - WPF 渐变画笔?

android - Textview 和 Seekbar 绑定(bind)到同一个属性,但是 textview 不显示更新的值