Wpf中集合对象绑定所在ViewModel的属性

要将集合中的对象绑定到 ViewModel 中的 Command,可以使用 ItemContainerStyle 和 Button 的 Command 属性来实现。

下面是一个示例,假设你有一个 ViewModel 类,其中有一个名为 Items 的可绑定集合属性,该集合包含多个 Item 对象。ViewModel 中还有一个名为 ButtonCommand 的命令属性。

csharp 复制代码
<ListBox ItemsSource="{Binding Items}">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">
                        <Button Content="Button" Command="{Binding DataContext.ButtonCommand, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}" CommandParameter="{Binding}" />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

在上面的示例中,我们使用 ItemContainerStyle 来自定义每个列表项的外观,使用 Button 元素来表示按钮。在按钮的 Command 属性中,我们使用了 RelativeSource 来找到 ListBox 的 DataContext(即 ViewModel),并将其中的 ButtonCommand 属性绑定为按钮的命令。CommandParameter 属性绑定了当前列表项的数据对象,这样在执行命令时可以传递该对象作为参数。

确保你在 MainWindow 的代码中正确设置 ViewModel,并在其中设置 Items 和 ButtonCommand 属性。同时,还需要实现 ButtonCommand 的逻辑。

这样,当你运行程序时,会为每个列表项生成一个按钮,并且按钮点击时会触发 ViewModel 中的 Command。

相关推荐
小北方城市网10 小时前
Redis 分布式锁高可用实现:从原理到生产级落地
java·前端·javascript·spring boot·redis·分布式·wpf
流水线上的指令侠19 小时前
补充说明——针对《C#:从 0 到 1 创建基于 NUnit + FlaUI 的 WPF UI 自动化测试项目》
功能测试·ui·c#·自动化·wpf
流水线上的指令侠20 小时前
C# 实战:从 0 到 1 搭建基于 NUnit + FlaUI 的 WPF UI 自动化测试项目
功能测试·ui·c#·自动化·wpf·visual studio
贾修行1 天前
.NET 全栈开发学习路线:从入门到分布式
c#·.net·wpf·asp.net core·web api·winforms·services
晓13131 天前
第四章:Redis实战应用及常见问题(下篇)
java·数据库·缓存·wpf
掘根2 天前
【jsonRpc项目】客户端的Requestor模块,RpcCaller模块
wpf
FuckPatience2 天前
WPF ListBoxItem绑定自己在ListBox中的顺序
wpf
天才奇男子3 天前
LVS原理及部署
linux·运维·云原生·wpf·lvs·linux chrony
予枫的编程笔记3 天前
【Redis实战进阶篇1】Redis 分布式锁:从手写实现到 Redisson 最佳实践
redis·分布式·wpf
小北方城市网4 天前
Spring Cloud Gateway 生产级实践:高可用架构、灰度发布与故障排查
spring boot·redis·分布式·缓存·架构·wpf