使用 C# 更新 wpf 中 StatusBar 中的文本

Arc*_*hie 5 wpf statusbar

我在 wpf 的 StatusBar 中有一个 TextBox,我想更新它。

我在 ListBox 中有一个文件列表。在每个文件上,我将通过调用方法 ProcessFile() 来执行一些操作。所以每当文件处理完成时,我想在状态栏文本中显示该文件的名称。

我试过这样的事情:

private void button_Click(object sender, RoutedEventArgs e)
    {
        
        statusBar.Visibility = Visibility.Visible;

        DispatcherFrame frame = new DispatcherFrame();
        Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(TimeConsumingMethod), frame);
        Dispatcher.PushFrame(frame);
        statusBar.Visibility = Visibility.Collapsed;
    }

    public object TimeConsumingMethod(Object arg)
    {
        ((DispatcherFrame)arg).Continue = false;
        
        foreach (string fileName in destinationFilesList.Items)
        {
            txtStatus.Text = fileName.ToString();
            //Assume that each process takes some time to complete
            System.Threading.Thread.Sleep(1000);
        }
        return null;
    }
Run Code Online (Sandbox Code Playgroud)

但是我只能在状态栏中看到最后一个文件的名称。代码有什么问题?我该如何纠正?

Jeh*_*hof 1

当您使用 ViewModel 时,我会在 ViewModel 中定义一个属性“ProcessedFile”,并将 StatusBar 的文本框绑定到该属性。

\n\n

每次处理文件时,我都会将属性“ProcessedFile”设置为文件名。

\n\n

Here\xc2\xb4s 是 ViewModel 的一些代码。

\n\n
public class ViewModel : INotifyPropertyChanged {\n    private string _processedFile;\n    public string ProcessedFile {\n        get {\n            return _processedFile;\n        }\n        set {\n\n            if (_processedFile != value) {\n                _processedFile = value;\n\n                if (PropertyChanged != null) {\n                    PropertyChanged(this, new PropertyChangedEventArgs("ProcessedFile"));\n                }\n            }\n        }\n    }\n\n    #region INotifyPropertyChanged Members\n\n    public event PropertyChangedEventHandler PropertyChanged;\n\n    #endregion\n\n    public void ProcessFile() {\n       // Process the file\n       ProcessedFile = //Set the Property to the processed file\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是将 TextBox 绑定到属性的 XAML。(我假设 ViewModel 设置为 TextBox 的 DataContext)

\n\n
<TextBox Text="{Binding ProcessedFile, Mode=OneWay}"/>\n
Run Code Online (Sandbox Code Playgroud)\n