0

我想通过操纵不透明度值在我的 GUI 上设置一个透明的控件。BackgroundWorker因此,我在我的 WPF-Form 的构造函数上初始化 a ,例如:

volumeWorker = new BackgroundWorker();
volumeWorker.DoWork += new DoWorkEventHandler(VolumeBarDoWork);
volumeWorker.ProgressChanged += new ProgressChangedEventHandler(VolumeBarChanged);
volumeWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(VolumeBarCompleted);
volumeWorker.WorkerReportsProgress = true;

之后,我的 GUI 等待一个由另一个类触发的事件

soundController = new SoundController();
soundController.VolumeChanged +=new SoundController.VolumeChangedEventHandler(VolumeChanged);

在事件处理程序上,我最终将启动 volumeWorker (BGW) 来操作 GUI:

private void VolumeChanged(float pVolume)
{
    Logger.InfoWrite("Event raised ## New volume : {0}", pVolume);
    volumeWorker.RunWorkerAsync();
}

但是在 BackgroundWorkers ChangeEvent 上,我每次都收到 InvalidOperationException。有人知道吗?

private void VolumeBarDoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;
    Logger.InfoWrite("Worker");
    for(int _opacity = 99 ; _opacity >= 0 ; _opacity--)
    {
        Logger.InfoWrite("Start on {0}", _opacity);
        worker.ReportProgress(_opacity);
        System.Threading.Thread.Sleep(20)
    }
    e.Result = e.Argument;
}

private void VolumeBarChanged(object sender, ProgressChangedEventArgs e)
{
    this.volumeBar.Opacity -= 0.01f;
    Logger.InfoWrite("Changed opacity to : {0} on {1}", this.volumeBar.Opacity, e.ProgressPercentage);
}

private void VolumeBarCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    Logger.InfoWrite("Completed");
    this.volumeBar.Opacity = 0.0f;
}
4

1 回答 1

1

您不能直接在 UI 线程之外更改 UI,因为 UI 控件是在 UI 线程上创建的。请改用Dispatcher.InvokeorBeginInvoke方法。

于 2012-04-19T07:41:09.877 回答