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。

相关推荐
aini_lovee9 小时前
33节点配电网分布式发电(DG)最优分布MATLAB实现
分布式·matlab·wpf
czhc11400756639 小时前
wpf 28
wpf
baivfhpwxf20239 小时前
WPF Binding 绑定 超详细详解
c#·wpf
数据知道10 小时前
MongoDB心跳检测与故障转移:自动主从切换的全过程解析
数据库·mongodb·wpf
Scout-leaf12 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
柒.梧.14 天前
基于SpringBoot+JWT 实现Token登录认证与登录人信息查询
wpf
十月南城17 天前
Flink实时计算心智模型——流、窗口、水位线、状态与Checkpoint的协作
大数据·flink·wpf
听麟20 天前
HarmonyOS 6.0+ 跨端会议助手APP开发实战:多设备接续与智能纪要全流程落地
分布式·深度学习·华为·区块链·wpf·harmonyos
@hdd20 天前
Kubernetes 可观测性:Prometheus 监控、日志采集与告警
云原生·kubernetes·wpf·prometheus
zls36536520 天前
C# WPF canvas中绘制缺陷分布map
开发语言·c#·wpf