Skip to content

Instantly share code, notes, and snippets.

@tmyt
Last active December 12, 2015 05:22
Show Gist options
  • Save tmyt/b68f99a9833b1096d765 to your computer and use it in GitHub Desktop.
Save tmyt/b68f99a9833b1096d765 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Linq;
using System.Reflection;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace Common.Extensions
{
/// <summary>
/// This is Darkness. It's workarounds for Runtime Bugs on TH2(10586).
/// </summary>
public class TH2Workarounds
{
private static bool IsTH2;
static TH2Workarounds()
{
var type = typeof(Windows.UI.Core.CoreWindow);
// PointerRoutedAway event available after TH2.
IsTH2 = type.GetRuntimeEvent("PointerRoutedAway") != null;
}
public static readonly DependencyProperty ReorderListViewItemProperty = DependencyProperty.RegisterAttached(
"ReorderListViewItem", typeof (bool), typeof (TH2Workarounds), new PropertyMetadata(default(bool), ReorderListViewItemPropertyChanged));
public static void SetReorderListViewItem(DependencyObject element, bool value)
{
element.SetValue(ReorderListViewItemProperty, value);
}
public static bool GetReorderListViewItem(DependencyObject element)
{
return (bool) element.GetValue(ReorderListViewItemProperty);
}
private static void ReorderListViewItemPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var view = d as ListViewBase;
if (view == null) return;
if ((bool) e.NewValue)
{
view.Drop += ListViewWorkaroundOnDrop;
view.DragItemsStarting += ListViewWorkaroundOnDragItemsStarting;
}
else
{
view.Drop -= ListViewWorkaroundOnDrop;
view.DragItemsStarting -= ListViewWorkaroundOnDragItemsStarting;
}
}
/// <summary>Workaround: TH2 (10586) ListView reorder issue.</summary>
private static void ListViewWorkaroundOnDragItemsStarting(object sender, DragItemsStartingEventArgs e)
{
if (!IsTH2) return;
var item = e.Items.First();
e.Data.Properties.Add("item", item);
e.Data.Properties.Add("source", sender);
}
/// <summary>Workaround: TH2 (10586) ListView reorder issue.</summary>
private static void ListViewWorkaroundOnDrop(object sender, DragEventArgs e)
{
if (!IsTH2) return;
var view = sender as ListViewBase;
if (view == null) return;
var pt = e.GetPosition(view);
var idx = view.Items.Count; ;
for (var i = 0; i < view.Items.Count; ++i)
{
var container = (FrameworkElement)view.ContainerFromIndex(i);
var trans = view.TransformToVisual(container);
var tpt = trans.TransformPoint(pt);
if (tpt.X < 0 || tpt.X > container.ActualWidth) continue;
idx = tpt.X < container.ActualWidth / 2 ? i : i + 1;
break;
}
var item = e.Data.Properties.Single(p => p.Key == "item").Value;
var from = view.Items.IndexOf(item);
if (from < idx) idx--;
var source = view.ItemsSource as IList;
if (source == null) return;
source.RemoveAt(from);
source.Insert(idx, item);
e.Handled = true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment