You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在XAML ListBox的每行中添加按钮?求技术解决方案

在ListBox每行添加按钮的解决方案

没问题,要给ListBox的每一行加上按钮,核心是用ItemTemplate自定义列表项的布局——你当前用的DisplayMemberPath只能展示单个属性,没法插入额外控件,替换成模板就能实现需求了。

我帮你修改了代码,保留了你原来的功能(比如Delete键绑定、选中项绑定),同时加入了行内按钮:

<ListBox Margin="5" 
         ItemsSource="{Binding WindowsLicenseKeys}" 
         HorizontalAlignment="Stretch" 
         SelectedItem="{Binding SelectedKey}" 
         Style="{StaticResource ListBoxNonScrollable}">
    <!-- 自定义列表项模板 -->
    <ListBox.ItemTemplate>
        <DataTemplate>
            <!-- 用Grid布局,分两列:一列显示Key,一列放按钮 -->
            <Grid ColumnDefinitions="*,Auto">
                <!-- 显示Key属性 -->
                <TextBlock Text="{Binding Key}" VerticalAlignment="Center"/>
                <!-- 行内删除按钮 -->
                <Button Grid.Column="1" 
                        Content="删除" 
                        Command="{Binding DataContext.RemoveKeyCommand, RelativeSource={RelativeSource AncestorType=ListBox}}"
                        CommandParameter="{Binding}"/>
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>

    <!-- 保留你原来的键盘绑定 -->
    <ListBox.InputBindings>
        <KeyBinding Gesture="Delete" 
                    Key="Delete" 
                    Command="{Binding DataContext.RemoveKeyCommand, ElementName=dg_keys}"/>
    </ListBox.InputBindings>
</ListBox>

关键部分说明:

  • 移除了DisplayMemberPath,因为我们用ItemTemplate完全自定义了项的内容
  • 用Grid做布局,确保按钮靠右,文本占满剩余空间
  • 按钮的Command通过RelativeSource找到ListBox的DataContext(也就是你的ViewModel),这样能正确绑定RemoveKeyCommand
  • CommandParameter="{Binding}"把当前列表项作为参数传递给命令,方便你的ViewModel知道要删除哪一项

如果需要添加其他按钮(比如编辑),直接在Grid里加对应的Button就行,逻辑和删除按钮一致~

内容的提问来源于stack exchange,提问作者Dragan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:20:11