Dynamically updating a WPF Window before code finishes executing

Viewed 2619

This is probably a really basic question, please bear with me, I'm still very new to the world of WPF/C#.

I have a WPF app where I open a new window if a button is clicked.

The window is called Sync and all it does is instantiate a viewmodel class which contains some public properties that are bound to my view.

The viewmodel also instantiates a class containing a lot of business logic, this updates the ViewModel's bound properties, the aim being to update the content of my window.

This sort of works, but only when all of the (sometimes quite lengthy) processing is completed does the window load and the view is populated with the last value of the ViewModel's properties.

I think I'm missing something pretty basic here. How do I get my window to instantly load and then have the view update when any of the properties have changed? Should I be listening for a PropertyChanged event and then updating the view? Where do i do this? Within the view model's setter?

Here's some simplified code:

Calling my window from my main window's View Model

public void SyncAction()
    {
        Sync syncWindow = new Sync();
        syncWindow.Show();
        syncWindow.Activate();
    }

The window

public partial class Sync : Window
{
    public Sync()
    {
        InitializeComponent();

        var viewModel = new SyncViewModel();
    }
}

The view model

class SyncViewModel
{

    private string _miscStatus = "";

    public SyncViewModel()
    {
        var sync = new SyncLogic();
        sync.SyncAll(this);
    }

    public string MiscStatus
    {
        get
        {
            return _miscStatus;
        }
        set
        {
            _miscStatus += value;
        }
    }
}

Some business logic

class SyncLogic
{
    private ViewModel.SyncViewModel _syncViewModel;

    public void SyncAll(ViewModel.SyncViewModel syncViewModel)
    {
        _syncViewModel = syncViewModel;

        // lock our synctime
        var syncTime = DateTools.getNow();

        _syncViewModel.MiscStatus = "Sync starting at " + syncTime.ToString();

        // Do lots of other stuff

        _syncViewModel.MiscStatus = String.Format("Sync finished at at {0}, total time taken {1}", 
            DateTools.getNow().ToString(), (DateTools.getNow() - syncTime).ToString());
    }
}

Bonus question: The way I'm updating the view from within my business logic (by passing in a reference to the viewmodel and updating its properties from there) seems a bit kludgy. I definitely want to keep the business logic separate, but am not sure how I can pass any output back out to the viewmodel. What would be a better way of doing this please?

5 Answers
Related