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

WPF C#中如何将ListView行传入CheckBox_Checked方法

解决ListView中CheckBox选中时获取对应行数据的问题

有两种实用方法可以实现你的需求,根据你的项目场景选择即可:


方法1:通过DataContext直接获取当前行数据

因为你的ListView已经绑定了自定义类集合,每行的DataContext就是对应的自定义类实例,直接在事件方法里提取即可:

XAML代码片段

<ListView ItemsSource="{Binding YourCustomCollection}">
    <ListView.View>
        <GridView>
            <!-- 其他列定义 -->
            <GridViewColumn>
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <CheckBox Checked="CheckBox_Checked" Unchecked="CheckBox_UnChecked" />
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

后台C#代码

private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
    var checkBox = sender as CheckBox;
    // 获取当前行绑定的自定义类对象
    var targetItem = checkBox.DataContext as YourCustomClass;
    
    // 这里可以直接操作targetItem,比如添加到选中集合
}

private void CheckBox_UnChecked(object sender, RoutedEventArgs e)
{
    var checkBox = sender as CheckBox;
    var targetItem = checkBox.DataContext as YourCustomClass;
    
    // 处理取消选中的逻辑,比如从选中集合移除
}

方法2:绑定IsChecked到自定义类属性(推荐MVVM场景)

如果你的项目遵循MVVM模式,直接给自定义类添加一个IsSelected属性,绑定到CheckBox的IsChecked,这样无需写后台事件,直接通过集合状态判断选中项:

自定义类实现(需实现属性变更通知)

public class YourCustomClass : INotifyPropertyChanged
{
    // 你的原有业务属性
    public string ItemName { get; set; }
    public int ItemValue { get; set; }

    private bool _isSelected;
    public bool IsSelected
    {
        get => _isSelected;
        set
        {
            _isSelected = value;
            OnPropertyChanged(nameof(IsSelected));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

XAML绑定代码

<ListView ItemsSource="{Binding YourCustomCollection}">
    <ListView.View>
        <GridView>
            <!-- 其他列定义 -->
            <GridViewColumn>
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}" />
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

获取选中项

在ViewModel或合适的逻辑层直接过滤集合:

var selectedItems = YourCustomCollection.Where(item => item.IsSelected).ToList();

这种方式逻辑更清晰,避免了后台事件的耦合,更适合绑定集合的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 10:05:24