WPF TextBlock绑定实现文件处理计数进度无实时更新问题求助
问题核心原因
- 绑定实例不匹配:XAML中硬编码实例化了
FfxTextEncoder作为绑定源,业务代码中又新建了另一个FfxTextEncoder实例处理逻辑,两个实例完全独立,更新业务实例的属性自然不会同步到UI - 未实现属性变更通知:
FfxTextEncoder没有实现INotifyPropertyChanged接口,属性变更时UI收不到通知 - 跨线程更新问题:使用多线程处理逻辑时直接在后台线程更新绑定属性,WPF不允许非UI线程更新绑定源,会导致更新失效
- 绑定路径错误:TextBlock绑定了
ActiveEntity属性但未对其赋值,绑定源为空
修复方案
1. 修正XAML绑定
删除硬编码的DataContext,简化绑定路径:
<materialDesign:Card x:Name="Card" Padding="32" Margin="16" Height="81" VerticalAlignment="Bottom"> <TextBlock x:Name="TextBlock" Style="{DynamicResource MaterialDesignTitleTextBlock}" HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding Data, Mode=OneWay}"/> </materialDesign:Card>
2. 给FfxTextEncoder实现属性变更通知,支持跨线程更新
using System.ComponentModel; using System.Runtime.CompilerServices; using System.Windows.Threading; using System.Threading; public class FfxTextEncoder : INotifyPropertyChanged { public int TotalFileCount { get; } private int _counter; private string _data; public string Data { get => _data; set { // 自动调度到UI线程更新属性 Dispatcher.CurrentDispatcher.Invoke(() => { _data = value; OnPropertyChanged(); }); } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } // 构造函数中预先计算总文件数 public FfxTextEncoder(YourDirType dirs) { _dirs = dirs; TotalFileCount = dirs.Files.Count; } // 保留原有其他业务代码 }
3. 修正业务逻辑的绑定关联
把业务中创建的实例赋值给UI绑定源,移除不必要的ConfigureAwait(false)避免丢失UI上下文:
private async Task TextDirectoryEncoder(FileSystemInfo fsoInfo) { if (fsoInfo is not DirectoryInfo info) return; try { var dirs = Util.LocalDir(info.FullName); var encoder = new FfxTextEncoder(dirs); // 关联业务实例和UI绑定源 Card.DataContext = encoder; var s = new SplashScreenWindow(); encoder._threads.Add(encoder.GetThreadId() + " in " + nameof(TextDirectoryEncoder)); s.Show(); // 不要加ConfigureAwait(false),保持UI上下文 await encoder.EncodeTextAsync(); _ = MessageBox.Show(encoder.Data ?? "Maybe all files is translated or text file is missing!"); } catch (Exception e) { _ = SimpleLog.Log(e.Message, SimpleLog.Severity.Exception); throw; } }
4. 修正计数逻辑,实现要求的进度格式
使用线程安全的计数方法,避免多线程下计数错误:
private async Task EncodeText(IFile item) { _threads.Add(GetThreadId() + " in task " + nameof(EncodeText)); if (item.FileText.Length is not 0) { // 线程安全的自增计数 var counter = Interlocked.Increment(ref _counter); // 输出 已处理/总数量 格式的进度文本,可自定义后缀提示 Data = $"{counter}/{TotalFileCount} 已处理完成"; _threads.Add(Data); _ = Directory.CreateDirectory( item.FileTranslated.DirectoryName ?? throw new InvalidOperationException()); // IO操作可以保留ConfigureAwait(false)切后台 await $@"{item.Application} -i -t {Applications.Table} {item.FileBin} {item.FileText.FullName} {item.FileTranslated.FullName}" .ExecuteTask().ConfigureAwait(false); } }
内容的提问来源于stack exchange,提问作者Rhadamants TriboGamer
相关产品推荐
相关产品推荐

