xPrajwalx xPrajwalx - 1 year ago 68
C# Question

Updating progress bar of another window

I'm trying to create a new window and show completion on it. I'm using BackgroundWorker report event to do that. And it updates local properties of window which are bound to ProgressBar and TextBox.

This is triggered when progress Changes

void copyBw_ProgressChanged(object sender, ProgressChangedEventArgs e)
//This is public method of child window which sets progress and text properties
cpw.ChangeCompletion(e.ProgressPercentage, UserDefinedFileName);

This is the method i'm using to set the properties

public void ChangeCompletion(int Value, string file){
Completion = Value;
FileCopiedString += file;

Below is my XAML

<ProgressBar Name="CopyProgress" Margin="0,41,-2,324" Width="634" Height="5" Maximum="100" Value="{Binding Completion, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}" Grid.ColumnSpan="2"/>
<Label Content="Please wait while files are getting copied ... " Margin="10,10,384,334" Grid.ColumnSpan="2"/>
<RichTextBox Name="CopyFileList" Margin="10,62,10,10" Grid.ColumnSpan="2">
<Run Text="{Binding FileCopiedString, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"/>

The value of both properties get changed but won't report it to UI.

I've checked many threads but couldn't find the solution. Any pointers on this would be really helpful.

Update: When I set the property of ProgressBar Directly, (Without binding) then it works.
CopyProgress.Value = Value;

But this is not right and binding should happen. Now I've narrowed it down to Binding problem but I don't know where the mistake is.

Answer Source

Finally, I've been able to resolve it. I think its a bit overkill but it worked.

I wasn't following MVVM. After I created a ViewModel and set that as default DataContext to View, it worked. When I tried to mix up with the ViewModel and View, eventhough it is supposed to work, it didn't.


enter public partial class Window1 : Window, INotifyPropertyChanged{
public Window1(){   
ProgressBarViewModel pbvm = new ProgressBarViewModel();
    DataContext = pbvm;


public partial class ProgressBarViewModel : INotifyPropertyChanged{
int _completion;
    public int Completion
        get { return _completion; }
            _completion = value;

private string _fileCopied;
public string FileCopiedString
    get { return _fileCopied; }
        _fileCopied = value;

public void ChangeCompletion(int Value, string file)
    Completion = Value;
    FileCopiedString = FileCopiedString + file;

public event PropertyChangedEventHandler PropertyChanged;

public void Notify(string name)
    if (PropertyChanged != null)
        PropertyChanged(this, new PropertyChangedEventArgs(name));


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download