Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@karno
Created December 19, 2013 07:23
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 karno/8035600 to your computer and use it in GitHub Desktop.
Save karno/8035600 to your computer and use it in GitHub Desktop.
using System;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Threading;
using Livet;
namespace Karno.Xac.Sample
{
public class MainWindowViewModel : ViewModel
{
private readonly DispatcherCollection<string> _collection =
new DispatcherCollection<string>(DispatcherHelper.UIDispatcher);
private readonly Stopwatch _stopwatch;
private readonly DispatcherTimer _timer;
private readonly DragAcceptDescription _description;
public DispatcherCollection<string> Collection
{
get { return this._collection; }
}
public DragAcceptDescription Description
{
get { return this._description; }
}
public double CurrentTimeSec
{
get { return _stopwatch.ElapsedMilliseconds / 1000.0; }
}
public MainWindowViewModel()
{
// prepare drag accept description
this._description = new DragAcceptDescription();
this._description.DragOver += this.OnDragOver;
this._description.DragDrop += this.OnDragDrop;
// start tick count
_stopwatch = new Stopwatch();
_timer = new DispatcherTimer(DispatcherPriority.Render)
{
Interval = TimeSpan.FromMilliseconds(10)
};
_timer.Tick += (_, e) => RaisePropertyChanged(() => CurrentTimeSec);
_timer.Start();
// create list
var rand = new Random(Environment.TickCount);
"にゃんぱすー"
.Select(c => c.ToString())
.OrderBy(_ => rand.Next())
.ForEach(_collection.Add);
}
public void Loaded()
{
_stopwatch.Start();
}
private void OnDragOver(DragEventArgs args)
{
if (args.AllowedEffects.HasFlag(DragDropEffects.Move) &&
args.Data.GetDataPresent(typeof(String)))
{
args.Effects = DragDropEffects.Move;
}
}
void OnDragDrop(DragEventArgs args)
{
// check and get data
if (!args.Data.GetDataPresent(typeof(String))) return;
var data = args.Data.GetData(typeof(String)) as string;
if (data == null) return;
var fe = args.OriginalSource as FrameworkElement;
if (fe == null) return;
var target = fe.DataContext as string;
if (target == null) return;
// move data
var si = _collection.IndexOf(data);
var di = _collection.IndexOf(target);
if (si < 0 || di < 0 || si == di) return;
_collection.Move(si, di);
// check にゃんぱすー
if (_collection.Select(s => s[0]).SequenceEqual("にゃんぱすー"))
{
Stop();
}
}
private void Stop()
{
_stopwatch.Stop();
_timer.Stop();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment