移动滑块直到达到值

时间:2014-06-25 23:32:44

标签: c# wpf while-loop slider

我试着"动画"某个值为true时滑块,直到达到指定值。但由于某种原因,它并不像我想象的那么容易:

while (depthScan == true)
{
    depth_max_slider.Value += 10;
    Console.WriteLine("Working");
    if (blobCount <= 400)
    {
        depth_max_slider.Value += 10;

    }
    else
    {
        depthScan = false;
    }

}

我做错了什么?

1 个答案:

答案 0 :(得分:0)

这样的事情应该可以解决问题...

public class MyWindow : Window
    {
        void StartButton_Click( object sender, RoutedEventArgs e )
        {
            // This method will run on the UI thread

            BackgroundWorker worker = new BackgroundWorker();

            worker.DoWork += worker_DoWork;
            worker.WorkerReportsProgress = true;
            worker.ProgressChanged += worker_ProgressChanged;

            worker.RunWorkerAsync(); // start the thread

            // UI thread continues immediately

            // exit click event handler, UI thread goes back to WPF control so it can keep rendering...
        }

        void worker_ProgressChanged( object sender, ProgressChangedEventArgs e )
        {
            // This method will run on the UI thread

            double depth_max = (double) e.UserState; // grab the value of depth_max passed over from background thread

            depth_max_slider.Value = depth_max; // update the slider with this value

            // exit ProgressChanged event handler, UI thread goes back to WPF control so it can keep rendering...
        }

        void worker_DoWork( object sender, DoWorkEventArgs e )
        {
            // This method will run on the background thread

            BackgroundWorker worker = sender as BackgroundWorker;

            int percentComplete = 0;
            double depth_max;

            while( depthScan == true )
            {
                depth_max += 10; // NOTE: don't touch the slider control from the background thread, use a double instead!

                worker.ReportProgress( percentComplete, depth_max ); // pass depth_max as the 2nd param, "user state", will show up in ProgressChangedEventArgs in ProgressChanged handler

                Console.WriteLine( "Working" );
                if( blobCount <= 400 )
                {
                    depth_max += 10;

                    worker.ReportProgress( percentComplete, depth_max );

                }
                else
                {
                    depthScan = false;
                }

            }
        }
    }