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

WPF DataGrid中点击行内下载按钮更新进度条的实现方法

WPF DataGrid行内Download按钮更新对应ProgressBar实现

核心前提:数据实体实现INotifyPropertyChanged

要让Progress属性变化时自动刷新UI,你的数据类必须实现这个接口,确保属性变更能通知到绑定的ProgressBar:

public class DownloadItem : INotifyPropertyChanged
{
    private int _progress;
    public int Progress
    {
        get => _progress;
        set
        {
            _progress = value;
            OnPropertyChanged(nameof(Progress));
        }
    }

    // 其他业务属性示例
    public string FileName { get; set; }

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

DataGrid列绑定配置

确保ProgressBar的Value绑定到实体的Progress属性,同时为每行配置Download按钮:

<DataGrid ItemsSource="{Binding DownloadItems}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="文件名" Binding="{Binding FileName}" />
        <DataGridTemplateColumn Header="下载进度">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ProgressBar Value="{Binding Progress}" Minimum="0" Maximum="100" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTemplateColumn Header="操作">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Content="Download" Click="BeginDownload_Click" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

按钮点击事件处理

在点击事件中直接获取当前行的实体对象,异步更新Progress属性(避免阻塞UI):

private async void BeginDownload_Click(object sender, RoutedEventArgs e)
{
    // 从按钮的DataContext拿到当前行的DownloadItem实例
    var btn = sender as Button;
    var targetItem = btn?.DataContext as DownloadItem;
    if (targetItem == null) return;

    // 模拟下载进度,实际替换为真实下载逻辑
    for (int progress = 0; progress <= 100; progress++)
    {
        targetItem.Progress = progress;
        await Task.Delay(50); // 模拟下载耗时
    }
}

关键说明

  • 无需额外找"选中行":按钮属于当前行的模板,其DataContext就是该行绑定的实体对象,直接获取最准确
  • 必须用异步操作:如果用同步循环,UI线程会被阻塞,ProgressBar无法实时更新
  • 属性变更通知是核心:实体类的INotifyPropertyChanged实现是绑定生效的前提,缺少它的话,即使修改Progress值,UI也不会刷新

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 11:45:34