Close Window when Thread finishes c# wpf xaml

Asked

Viewed 17 times

0

How do I close the Window after the thread runs ? This error is given: System.Invalidoperationexception: 'The call thread cannot access this object because it belongs to a different thread.'

Progressbar:

 <Grid>
    <ProgressBar Width="250" Height="35" Minimum="0" Maximum="100"
                 Value="{Binding WorkerState}"></ProgressBar>
</Grid>

Call from Window:

 private void btnBuscarCep_Click(object sender, RoutedEventArgs e)
    {
        ProgressBar progressBar = new ProgressBar();
        progressBar.ShowDialog();

    }

Window:

    public partial class ProgressBar : Window, INotifyPropertyChanged
{
    private BackgroundWorker _bgWorker = new BackgroundWorker();
    private int _workerState;

    public event PropertyChangedEventHandler PropertyChanged;

    public int WorkerState
    {
        get { return _workerState;}
        set
        {
            _workerState = value;
            if(PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("WorkerState"));
            }
        }
    }
    public ProgressBar()
    {
        InitializeComponent();

        DataContext = this;

        _bgWorker.DoWork += (s, e) => 
        { 
            for (int i = 0; i <= 100; i++)
            {
                System.Threading.Thread.Sleep(100);
                WorkerState = i;
            }
            
            //O Erro Ocorre Aqui
            Application.Current.MainWindow.Dispatcher.Invoke(() =>
            {
                Application.Current.MainWindow.Close();
            });
        };

        _bgWorker.RunWorkerAsync();
                
    }
}
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.