3

下面的两个代码段位于不同的命名空间中。第二个代码的访问修饰符是内部的。我正在那里做一些操作,我想计算百分比并在 MgmntApp 进度条中更新。我怎样才能做到这一点?

WpfApplication1

主窗口.xaml

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid Height="204">
        <ProgressBar Height="35" HorizontalAlignment="Left" Margin="57,83,0,0" Name="progressBar1" VerticalAlignment="Top" Width="346" />
    </Grid>
</Window>

我想在下面的类中进行长时间运行的操作时更新进度条的值。

不同的

文件解析器.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Different
{
    /// <summary>
    /// </summary>
    internal class FileParser:ImageFileParser
    {
        ImageFileParser.GenerateCmds()
        {
            percentage=change;    //0 to 100
            //long time operation
        }
    }
}
4

2 回答 2

2

如果解析需要很长时间,您可能希望在单独的线程上运行它。

您可以在进度更改时在 FileParser 上引发事件并在 MainWindow 中订阅此事件:

private void StartParsing()
{
    FileParser fp = new FileParser("FileName.txt");
    fp.ProgressChanged += FileParser_ProgressChanged;
    Thread t = new Thread(fp.GenerateCmds);
    t.Start();
}

private void FileParser_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    // switch to the UI thread if fileparser is running on a different thread
    Dispatcher.BeginInvoke(new Action(
                              () => { progressbar.Value = e.ProgressPercentage; }));
}

为此,您需要将事件添加到 FileParser:

internal class FileParser:ImageFileParser
{
    internal event EventHandler<ProgressChangedEventArgs> ProgressChanged;

    ImageFileParser.GenerateCmds()
    {
        percentage=change;    //0 to 100
        OnProgressChanged(percentage);
        //long time operation
    }

    internal protected void OnProgressChanged(int percentage)
    {
        var p = ProgressChanged;
        if(p != null)
        {
            p(this, new ProgressChangedEventArgs(percentage, null));
        }
    }
}
于 2012-05-22T07:24:08.560 回答
1

为什么不直接绑定到FileParser类的属性?

<ProgressBar Value="{Binding MyFileParser.PercentComplete}" ...

然后让FileParser实现INotifyPropertyChanged

internal class FileParser:ImageFileParser, INotifyPropertyChanged
{
    private decimal _pct;
    internal decimal PercentComplete { 
        get { return _pct; }
        set {
            _pct = value;
            PropertyChanged(this, new PropertyChangedEventArgs("PercentComplete"));
        }
    }
    PropertyChanged(this, new PropertyChangedEventArgs(info));

    ImageFileParser.GenerateCmds()
    {
        PercentComplete = change;    //0 to 100
        //long time operation
    }
}

然后只需根据需要更新PercentComplete属性...

于 2012-05-22T07:17:05.197 回答