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

如何在ViewModel中捕获Canvas的ItemsSource集合内的按钮点击事件

实现方案

步骤1:完善ViewModel代码

首先在你的MyViewModel中添加选中项存储属性和点击命令:

  • 首先确保你的ViewModel已经实现了INotifyPropertyChanged接口
  • 添加对应属性和命令定义:
// 此处替换为你FilteredLocations集合实际的元素类型,示例为LocationModel
private LocationModel _selectedLocation;
public LocationModel SelectedLocation
{
    get => _selectedLocation;
    set 
    { 
        _selectedLocation = value;
        OnPropertyChanged(); // 触发属性变更通知
    }
}

// 点击命令,可直接使用MVVM工具库的RelayCommand/DelegateCommand,也可自行实现ICommand
public ICommand LocationClickCommand { get; }

// 在ViewModel构造函数中初始化命令
public MyViewModel()
{
    LocationClickCommand = new RelayCommand<LocationModel>(clickedItem => 
    {
        // 把点击的按钮对应数据赋值给存储属性,完成需求
        SelectedLocation = clickedItem;
    });
}

注:如果没有引入第三方MVVM库,可以自行实现基础的RelayCommand,也可以使用WPF原生的RoutedCommand完成逻辑

步骤2:修改XAML绑定逻辑

在现有AnimatedButton的Style中补充Command和CommandParameter的绑定,修改后的Style代码如下:

<Style TargetType="tgr:AnimatedButton" >
    <Setter Property="ButtonBrush" Value="Red" />
    <Setter Property="Canvas.Left" Value="{Binding Position.X,RelativeSource={RelativeSource Self}}"/>
    <Setter Property="Canvas.Top" Value="{Binding Position.Y,RelativeSource={RelativeSource Self}}"/>
    <!-- 新增以下两个绑定配置 -->
    <Setter Property="Command" Value="{Binding DataContext.LocationClickCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}"/>
    <Setter Property="CommandParameter" Value="{Binding}"/>
</Style>

绑定逻辑说明:

  • Command通过RelativeSource向上查找父级ItemsControl的DataContext(也就是你的MyViewModel实例),绑定到我们定义的点击命令
  • CommandParameter直接绑定当前按钮对应的DataContext,也就是点击的按钮在集合中对应的完整数据对象

完成以上修改后,任意按钮被点击时,命令都会自动执行,将被点击的按钮对应数据赋值到ViewModel的SelectedLocation属性中。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 19:48:01