Timer in View Model

Dec 20, 2010 at 12:49 PM

Hi, I have service class in external assembly, I inject this class in view model class with MEF. I  need call service method every 3-4 seconds from view model.

I get from service new data as Dictionary<string,class>. This Dictionary is bind to listbox in view. And I need refresh with this data listbox in view.

In my solution I use DispatcherTimer, but I am absolute begginer in calibur.micto also MVVM and WPF. I don’t know what is a suitable solution in my case. So if someone have advance I will be gratefull.

My solution is here:

    [Export("MainScreen", typeof(IMainViewModel))]
public class MainViewModel : Screen, IMainViewModel
{

[Import]
private Service _service;//import with MEF from external assembly
[Import]
private Connection _conn;//import with MEF from external assembly

//this dictionary is bind to the listbox in view
private MyObservableDictionary<string, User> _users = null;

//temp dictionry
private MyObservableDictionary<string, User> _freshUsers = null;

private int _selectedUserIndex;

private DispatcherTimer _dispatcherTimer;


public Account Account{ get; set;}

public int SelectedUsersIndex
{
get { return _selectedUserIndex; }
set
{
_selectedUserIndex = value;
NotifyOfPropertyChange("SelectedUsersIndex");
}
}



public MainViewModel()
{
_dispatcherTimer = new DispatcherTimer();
_dispatcherTimer.Tick += DispatcherTimer_Tick;
_dispatcherTimer.Interval = TimeSpan.FromSeconds(3);
_dispatcherTimer.Start();
}


//I get every 3-4 sec from server new JSON data and I need update with this data listbox in view
private void DispatcherTimer_Tick(object sender, EventArgs eventArgs)
{
//server ping, call service method
Account.Ping = _service.Ping(Account);

//Refresh data in dictionary
_freshUsers = _service.LoadUsers(Account);
_users.Clear();
SelectedUsersIndex = 1;

foreach (var freshUser in _freshUsers)
{
_users.Add(freshUser);
}

//check if you have new messanges
if (Account.Ping.Rp > 0)
{
//load new messanges
for (int i = 0; i < Account.Ping.Rp; i++)
{
#region load rp
try
{
Rp message = _service.LoadRp(Account);

if (message != null)
{
//show messages
}
}
catch (Exception exception)
{
if (exception.Message == "You haven&#8217;t any messanged")
{

}
throw exception;// how handle show this exception in view?
}
#endregion
}
}
}
}