Skip to content

Instantly share code, notes, and snippets.

@robertiagar
Created October 4, 2013 09:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertiagar/6823610 to your computer and use it in GitHub Desktop.
Save robertiagar/6823610 to your computer and use it in GitHub Desktop.
main view model for a test app.
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Threading;
using Microsoft.AspNet.SignalR.Client.Hubs;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using Windows.ApplicationModel.Core;
namespace ChatApp.WindowsStore.ViewModel
{
/// <summary>
/// This class contains properties that the main View can data bind to.
/// <para>
/// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
/// </para>
/// <para>
/// You can also use Blend to data bind with the tool's support.
/// </para>
/// <para>
/// See http://www.galasoft.ch/mvvm
/// </para>
/// </summary>
public class MainViewModel : ViewModelBase
{
HubConnection _hubConnection;
IHubProxy _proxy;
ObservableCollection<string> _messages;
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
_hubConnection = new HubConnection("http://localhost:18479/");
_proxy = _hubConnection.CreateHubProxy("ChatHub");
_messages = new ObservableCollection<string>();
_messages.Add("test");
_messages.Add("test2");
_proxy.On<string, string>("SendMessage", (username, message) => SendMessage(username, message));
this.SendMessageCommand = new RelayCommand(async() => await this.SendToServer());
_hubConnection.Start();
}
private void SendMessage(string username, string message)
{
try
{
DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
_messages.Add(string.Format("{0}: {1}", username, message));
});
}
catch (Exception ex)
{
_messages.Add(ex.Message);
}
}
private async Task SendToServer()
{
await _proxy.Invoke("SendMessage", Username, Message);
}
public IList<string> Messages
{
get { return _messages; }
}
public ICommand SendMessageCommand { get; private set; }
private string _message;
public string Message
{
get { return _message; }
set
{
_message = value;
RaisePropertyChanged(() => Message);
}
}
private string _username;
public string Username
{
get { return _username; }
set
{
_username = value;
RaisePropertyChanged(() => Username);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment