RazvanR104
RazvanR104

Reputation: 73

C# - WPF - update progressbar from another class

I'm here to ask for some help regarding C# and especially WPF. :D

I have a WPF project and I need to update the value of a progressbar from another class. The progressbar is in class 'NdWindow' and I need to update its value from class 'Automator'.

I already tried some things but nothing worked for me.

In 'NdWindow' class:

public partial class NdWindow : Window
{
    public NdWindow()
    {
        InitializeComponent();
    }

    public NdWindow(int progress)
    {
        InitializeComponent();
        setprogress(progress);
    }

    public void setprogress(int progress)
    {
        this.progressBar.Value = progress;
        MessageBox.Show(Convert.ToString(progress));
    }

And in 'Automator' class:

public static void post()
{
    NdWindow test = new NdWindow();
    test.setprogress(10);
}

If I run the program, the MessageBox popups and shows me the value I have sent within setprogress(). I also tried sending the value within the constructor but it didn't help.

Please help me if you can. :D

Thanks!

PS: the 'post' function is executed by a button click. I have not written that code here. I hope this isn't a problem for you. :-)

Upvotes: 0

Views: 2764

Answers (1)

Dmitrii Dovgopolyi
Dmitrii Dovgopolyi

Reputation: 6299

In your post method you create new NdWindow, witch is not the window, where you want to change progressbar value.

You should somehow get NdWindow in Automator class.

public class Automator
{
   private NdWindow ndWindow;
   public Automator(NdWindow ndwindow)
   {
       this.ndWindow = ndwindow;
   }

   public void Post()
   {
       ndWindow.setprogress(10);
   }
}

public partial class NdWindow : Window
{
    private Automator automator;
    public NdWindow()
    {
        InitializeComponent();
        this.automator = new Automator(this);
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        Automator.Post();
    }
}

Or you could send NdWindow to your post method

public class Automator
{
   public static void Post(NdWindow ndWindow)
   {
       ndWindow.setprogress(10);
   }
}

public partial class NdWindow : Window
{
    private void button1_Click(object sender, RoutedEventArgs e)
    {
        Automator.Post(this);
    }
}

Upvotes: 3

Related Questions