如何在WPF中的不同线程中运行进度条?

时间:2011-02-02 06:39:51

标签: wpf multithreading .net-4.0 progress-bar

我正在动态填充列表视图项。同时我想显示一个进度条。填充数据时,应禁用进度条。如何实现这一目标。 我是WPF的新手。

2 个答案:

答案 0 :(得分:4)

您可以使用BackgroundWorker类,它可以在您使用WPF时简化后台线程的处理。 网上有很多这方面的例子。这里有两个来自codeproject,但很容易找到更多的例子:

http://www.codeproject.com/Tips/83317/BackgroundWorker-and-ProgressBar-demo.aspx http://www.codeproject.com/KB/cpp/BackgroundWorker_Threads.aspx

答案 1 :(得分:1)

我更喜欢通过演示模型控制视图状态。当视图需要将地址中的项填充到启动工作线程并在UI同步上下文中更新其进度值的表示模型时。

public class SampleModel : ObservableObject
{
    private ObservableCollection<string> _items = new ObservableCollection<string>();
    public IEnumerable<string> Items
    {
        get
        {
            return this._items;
        }
    }

    private int _progress;
    public int Progress
    {
        get
        {
            return this._progress;
        }
        set
        {
            if (this._progress != value)
            {
                this._progress = value;
                this.OnPropertyChanged("Progress");
            }
        }
    }

    public void Fill()
    {
        this.Progress = 0;
        var sc = SynchronizationContext.Current;

        new Thread(new ThreadStart(() =>
            {
                for (int i = 0; i < 100; i++)
                {
                    sc.Post(p =>
                        {
                            this._items.Add(i.ToString());
                            this.Progress ++;
                        }, null);
                    Thread.Sleep(100);
                }

                sc.Post(p =>
                {
                    this.Progress = 0;
                }, null);

            }))
            .Start();
    }
}

XAML:

<DockPanel>
    <ProgressBar Minimum="0"
                 Maximum="100"
                 Height="50"
                 Value="{Binding Progress}"
                 DockPanel.Dock="Top">
        <ProgressBar.Style>
            <Style TargetType="ProgressBar">
                <Setter Property="IsEnabled"
                        Value="True"/>
            </Style>
        </ProgressBar.Style>
    </ProgressBar>
    <Button Name="Start"
            DockPanel.Dock="Top">Start</Button>
    <ListView Name="List" 
              ItemsSource="{Binding Items}"/>
</DockPanel>

代码背后:

    public MainWindow()
    {
        InitializeComponent();
        this.Model = new SampleModel();
        this.Start.Click += new RoutedEventHandler(Start_Click);
    }

    void Start_Click(object sender, RoutedEventArgs e)
    {
        this.Model.Fill();
    }

    protected SampleModel Model
    {
        get
        {
            return (SampleModel)this.DataContext;   
        }
        set 
        {
            this.DataContext = value;
        }
    }