This commit is contained in:
liufei
2021-04-13 15:26:19 +08:00
parent cc399e2ef7
commit 5f38782623
26 changed files with 1778 additions and 1787 deletions

View File

@@ -1,10 +1,4 @@
using System; using System.Windows;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace GeekDesk namespace GeekDesk
{ {

View File

@@ -50,7 +50,7 @@ namespace DraggAnimatedPanelExample
/// <param name = "canExecuteMethod">Delegate to execute when CanExecute is called on the command. This can be null.</param> /// <param name = "canExecuteMethod">Delegate to execute when CanExecute is called on the command. This can be null.</param>
/// <exception cref = "ArgumentNullException">When both <paramref name = "executeMethod" /> and <paramref name = "canExecuteMethod" /> ar <see langword = "null" />.</exception> /// <exception cref = "ArgumentNullException">When both <paramref name = "executeMethod" /> and <paramref name = "canExecuteMethod" /> ar <see langword = "null" />.</exception>
public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod) public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod)
: base((o) => executeMethod((T) o), (o) => canExecuteMethod((T) o)) : base((o) => executeMethod((T)o), (o) => canExecuteMethod((T)o))
{ {
if (executeMethod == null || canExecuteMethod == null) if (executeMethod == null || canExecuteMethod == null)
throw new ArgumentNullException("executeMethod"); throw new ArgumentNullException("executeMethod");

13
Constant/AppConstant.cs Normal file
View File

@@ -0,0 +1,13 @@
using System;
namespace GeekDesk.Constant
{
class AppConstant
{
private static string APP_DIR = AppDomain.CurrentDomain.BaseDirectory.Trim();
/// <summary>
/// app数据文件路径
/// </summary>
public static string DATA_FILE_PATH = APP_DIR + "//Data"; //app数据文件路径
}
}

View File

@@ -1,10 +1,4 @@
using System; /// <summary>
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// 默认参数 /// 默认参数
/// </summary> /// </summary>
namespace GeekDesk.Constant namespace GeekDesk.Constant

View File

@@ -1,10 +1,4 @@
using System; namespace GeekDesk.Constant
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GeekDesk.Constant
{ {
enum SortType enum SortType
{ {

View File

@@ -2,183 +2,181 @@
using System; using System;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input; using System.Windows.Input;
using System.Windows.Media; using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
namespace DraggAnimatedPanel namespace DraggAnimatedPanel
{ {
/// <summary> /// <summary>
/// Description of SafariPanel_Drag. /// Description of SafariPanel_Drag.
/// </summary> /// </summary>
public partial class DraggAnimatedPanel public partial class DraggAnimatedPanel
{ {
#region const drag #region const drag
const double mouseDif = 2d; const double mouseDif = 2d;
const int mouseTimeDif = 25; const int mouseTimeDif = 25;
#endregion #endregion
#region private #region private
UIElement __draggedElement; UIElement __draggedElement;
public UIElement _draggedElement { public UIElement _draggedElement
get { return __draggedElement; } {
set get { return __draggedElement; }
{ set
__draggedElement = value; {
} __draggedElement = value;
} }
int _draggedIndex; }
int _draggedIndex;
bool _firstScrollRequest = true;
ScrollViewer _scrollContainer; bool _firstScrollRequest = true;
ScrollViewer scrollViewer ScrollViewer _scrollContainer;
{ ScrollViewer scrollViewer
get {
{ get
if (_firstScrollRequest && _scrollContainer == null) {
{ if (_firstScrollRequest && _scrollContainer == null)
_firstScrollRequest = false; {
_scrollContainer = (ScrollViewer)GetParent(this as DependencyObject, (ve)=>ve is ScrollViewer); _firstScrollRequest = false;
} _scrollContainer = (ScrollViewer)GetParent(this as DependencyObject, (ve) => ve is ScrollViewer);
return _scrollContainer; }
} return _scrollContainer;
} }
#endregion }
#endregion
#region private drag
double _lastMousePosX; #region private drag
double _lastMousePosY; double _lastMousePosX;
int _lastMouseMoveTime; double _lastMousePosY;
double _x; int _lastMouseMoveTime;
double _y; double _x;
Rect _rectOnDrag; double _y;
#endregion Rect _rectOnDrag;
#endregion
void OnMouseMove(object sender,MouseEventArgs e)
{ void OnMouseMove(object sender, MouseEventArgs e)
if (e.LeftButton == MouseButtonState.Pressed && _draggedElement == null && !this.IsMouseCaptured) {
StartDrag(e); if (e.LeftButton == MouseButtonState.Pressed && _draggedElement == null && !this.IsMouseCaptured)
else if (_draggedElement != null) StartDrag(e);
OnDragOver(e); else if (_draggedElement != null)
} OnDragOver(e);
}
void OnDragOver(MouseEventArgs e)
{ void OnDragOver(MouseEventArgs e)
Point mousePos = Mouse.GetPosition(this); {
double difX = mousePos.X - _lastMousePosX; Point mousePos = Mouse.GetPosition(this);
double difY = mousePos.Y - _lastMousePosY; double difX = mousePos.X - _lastMousePosX;
double difY = mousePos.Y - _lastMousePosY;
int timeDif = e.Timestamp - _lastMouseMoveTime;
if ((Math.Abs(difX) > mouseDif || Math.Abs(difY) > mouseDif) && timeDif > mouseTimeDif) int timeDif = e.Timestamp - _lastMouseMoveTime;
{ if ((Math.Abs(difX) > mouseDif || Math.Abs(difY) > mouseDif) && timeDif > mouseTimeDif)
//this lines is for keepn draged item inside control bounds {
DoScroll(); //this lines is for keepn draged item inside control bounds
DoScroll();
if (_x + difX < _rectOnDrag.Location.X)
_x = 0; if (_x + difX < _rectOnDrag.Location.X)
else if (ItemsWidth + _x + difX > _rectOnDrag.Location.X + _rectOnDrag.Width) _x = 0;
_x = _rectOnDrag.Location.X + _rectOnDrag.Width - ItemsWidth; else if (ItemsWidth + _x + difX > _rectOnDrag.Location.X + _rectOnDrag.Width)
else if (mousePos.X > _rectOnDrag.Location.X && mousePos.X < _rectOnDrag.Location.X + _rectOnDrag.Width) _x = _rectOnDrag.Location.X + _rectOnDrag.Width - ItemsWidth;
_x += difX; else if (mousePos.X > _rectOnDrag.Location.X && mousePos.X < _rectOnDrag.Location.X + _rectOnDrag.Width)
if (_y + difY < _rectOnDrag.Location.Y) _x += difX;
_y = 0; if (_y + difY < _rectOnDrag.Location.Y)
else if (ItemsHeight + _y + difY > _rectOnDrag.Location.Y + _rectOnDrag.Height) _y = 0;
_y = _rectOnDrag.Location.Y + _rectOnDrag.Height - ItemsHeight; else if (ItemsHeight + _y + difY > _rectOnDrag.Location.Y + _rectOnDrag.Height)
else if (mousePos.Y > _rectOnDrag.Location.Y && mousePos.Y < _rectOnDrag.Location.Y + _rectOnDrag.Height) _y = _rectOnDrag.Location.Y + _rectOnDrag.Height - ItemsHeight;
_y += difY; else if (mousePos.Y > _rectOnDrag.Location.Y && mousePos.Y < _rectOnDrag.Location.Y + _rectOnDrag.Height)
//lines ends _y += difY;
//lines ends
AnimateTo(_draggedElement,_x,_y, 0);
_lastMousePosX = mousePos.X; AnimateTo(_draggedElement, _x, _y, 0);
_lastMousePosY = mousePos.Y; _lastMousePosX = mousePos.X;
_lastMouseMoveTime = e.Timestamp; _lastMousePosY = mousePos.Y;
SwapElement(_x + ItemsWidth/2 , _y + ItemsHeight/2); _lastMouseMoveTime = e.Timestamp;
} SwapElement(_x + ItemsWidth / 2, _y + ItemsHeight / 2);
} }
}
void StartDrag(MouseEventArgs e)
{ void StartDrag(MouseEventArgs e)
Point mousePos = Mouse.GetPosition(this); {
_draggedElement = GetChildThatHasMouseOver(); Point mousePos = Mouse.GetPosition(this);
if (_draggedElement == null) _draggedElement = GetChildThatHasMouseOver();
return; if (_draggedElement == null)
_draggedIndex = Children.IndexOf(_draggedElement); return;
_rectOnDrag = VisualTreeHelper.GetDescendantBounds(this); _draggedIndex = Children.IndexOf(_draggedElement);
Point p = GetItemVisualPoint(_draggedElement); _rectOnDrag = VisualTreeHelper.GetDescendantBounds(this);
_x = p.X; Point p = GetItemVisualPoint(_draggedElement);
_y = p.Y; _x = p.X;
SetZIndex(_draggedElement,1000); _y = p.Y;
_lastMousePosX = mousePos.X; SetZIndex(_draggedElement, 1000);
_lastMousePosY = mousePos.Y; _lastMousePosX = mousePos.X;
_lastMouseMoveTime = e.Timestamp; _lastMousePosY = mousePos.Y;
this.InvalidateArrange(); _lastMouseMoveTime = e.Timestamp;
e.Handled = true; this.InvalidateArrange();
this.CaptureMouse(); e.Handled = true;
} this.CaptureMouse();
}
void OnMouseUp(object sender,MouseEventArgs e)
{ void OnMouseUp(object sender, MouseEventArgs e)
if (this.IsMouseCaptured) {
ReleaseMouseCapture(); if (this.IsMouseCaptured)
} ReleaseMouseCapture();
}
void SwapElement(double x, double y)
{ void SwapElement(double x, double y)
int index = GetIndexFromPoint(x,y); {
if (index == _draggedIndex || index < 0) int index = GetIndexFromPoint(x, y);
return; if (index == _draggedIndex || index < 0)
if (index >= Children.Count) return;
index = Children.Count - 1; if (index >= Children.Count)
index = Children.Count - 1;
int[] parameter = new int[]{_draggedIndex, index};
if (SwapCommand != null && SwapCommand.CanExecute(parameter)) int[] parameter = new int[] { _draggedIndex, index };
{ if (SwapCommand != null && SwapCommand.CanExecute(parameter))
SwapCommand.Execute(parameter); {
_draggedElement = Children[index]; //this is bcause after changing the collection the element is other SwapCommand.Execute(parameter);
FillNewDraggedChild(_draggedElement); _draggedElement = Children[index]; //this is bcause after changing the collection the element is other
_draggedIndex = index; FillNewDraggedChild(_draggedElement);
} _draggedIndex = index;
}
this.InvalidateArrange();
} this.InvalidateArrange();
}
void FillNewDraggedChild(UIElement child)
{ void FillNewDraggedChild(UIElement child)
if (child.RenderTransform as TransformGroup == null) {
if (child.RenderTransform as TransformGroup == null)
{ {
child.RenderTransformOrigin = new Point(0.5, 0.5); child.RenderTransformOrigin = new Point(0.5, 0.5);
TransformGroup group = new TransformGroup(); TransformGroup group = new TransformGroup();
child.RenderTransform = group; child.RenderTransform = group;
group.Children.Add(new TranslateTransform()); group.Children.Add(new TranslateTransform());
} }
SetZIndex(child,1000); SetZIndex(child, 1000);
AnimateTo(child,_x,_y, 0); //need relocate the element AnimateTo(child, _x, _y, 0); //need relocate the element
} }
void OnLostMouseCapture(object sender,MouseEventArgs e) void OnLostMouseCapture(object sender, MouseEventArgs e)
{ {
FinishDrag(); FinishDrag();
} }
void FinishDrag() void FinishDrag()
{ {
if (_draggedElement != null) if (_draggedElement != null)
{ {
SetZIndex(_draggedElement,0); SetZIndex(_draggedElement, 0);
_draggedElement = null; _draggedElement = null;
this.InvalidateArrange(); this.InvalidateArrange();
} }
} }
void DoScroll() void DoScroll()
{ {
if (scrollViewer != null) if (scrollViewer != null)
{ {
Point position = Mouse.GetPosition(scrollViewer); Point position = Mouse.GetPosition(scrollViewer);
double scrollMargin = Math.Min(scrollViewer.FontSize * 2, scrollViewer.ActualHeight / 2); double scrollMargin = Math.Min(scrollViewer.FontSize * 2, scrollViewer.ActualHeight / 2);
if (position.X >= scrollViewer.ActualWidth - scrollMargin && if (position.X >= scrollViewer.ActualWidth - scrollMargin &&
@@ -201,5 +199,5 @@ namespace DraggAnimatedPanel
} }
} }
} }
} }
} }

View File

@@ -1,237 +1,234 @@
/*Developed by (doiTTeam)=>doiTTeam.mail = devdoiTTeam@gmail.com*/ /*Developed by (doiTTeam)=>doiTTeam.mail = devdoiTTeam@gmail.com*/
using System; using System;
using System.Linq; using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input; using System.Windows.Input;
using System.Windows.Media; using System.Windows.Media;
using System.Windows.Media.Animation; using System.Windows.Media.Animation;
using System.Windows.Navigation;
namespace DraggAnimatedPanel namespace DraggAnimatedPanel
{ {
/// <summary> /// <summary>
/// Description of DraggAnimatedPanel. /// Description of DraggAnimatedPanel.
/// </summary> /// </summary>
public partial class DraggAnimatedPanel : WrapPanel public partial class DraggAnimatedPanel : WrapPanel
{ {
#region private vars #region private vars
Size _calculatedSize; Size _calculatedSize;
bool _isNotFirstArrange = false; bool _isNotFirstArrange = false;
int columns, rows; int columns, rows;
#endregion #endregion
static DraggAnimatedPanel() static DraggAnimatedPanel()
{ {
DefaultStyleKeyProperty.OverrideMetadata(typeof(DraggAnimatedPanel), new FrameworkPropertyMetadata(typeof(DraggAnimatedPanel))); DefaultStyleKeyProperty.OverrideMetadata(typeof(DraggAnimatedPanel), new FrameworkPropertyMetadata(typeof(DraggAnimatedPanel)));
} }
public DraggAnimatedPanel() : base() public DraggAnimatedPanel() : base()
{ {
this.AddHandler(Mouse.MouseMoveEvent, new MouseEventHandler(OnMouseMove), false); this.AddHandler(Mouse.MouseMoveEvent, new MouseEventHandler(OnMouseMove), false);
this.MouseLeftButtonUp += OnMouseUp; this.MouseLeftButtonUp += OnMouseUp;
this.LostMouseCapture += OnLostMouseCapture; this.LostMouseCapture += OnLostMouseCapture;
} }
UIElement GetChildThatHasMouseOver() UIElement GetChildThatHasMouseOver()
{ {
return GetParent(Mouse.DirectlyOver as DependencyObject, (ve) => Children.Contains(ve as UIElement)) as UIElement; return GetParent(Mouse.DirectlyOver as DependencyObject, (ve) => Children.Contains(ve as UIElement)) as UIElement;
} }
Point GetItemVisualPoint(UIElement element) Point GetItemVisualPoint(UIElement element)
{ {
TransformGroup group = (TransformGroup)element.RenderTransform; TransformGroup group = (TransformGroup)element.RenderTransform;
TranslateTransform trans = (TranslateTransform)group.Children[0]; TranslateTransform trans = (TranslateTransform)group.Children[0];
return new Point(trans.X, trans.Y); return new Point(trans.X, trans.Y);
} }
int GetIndexFromPoint(double x, double y) int GetIndexFromPoint(double x, double y)
{ {
int columnIndex = (int)Math.Truncate(x / itemContainterWidth); int columnIndex = (int)Math.Truncate(x / itemContainterWidth);
int rowIndex = (int)Math.Truncate(y / itemContainterHeight); int rowIndex = (int)Math.Truncate(y / itemContainterHeight);
return columns * rowIndex + columnIndex; return columns * rowIndex + columnIndex;
} }
int GetIndexFromPoint(Point p) int GetIndexFromPoint(Point p)
{ {
return GetIndexFromPoint(p.X, p.Y); return GetIndexFromPoint(p.X, p.Y);
} }
#region dependency properties #region dependency properties
public static readonly DependencyProperty ItemsWidthProperty = public static readonly DependencyProperty ItemsWidthProperty =
DependencyProperty.Register( DependencyProperty.Register(
"ItemsWidth", "ItemsWidth",
typeof(double), typeof(double),
typeof(DraggAnimatedPanel), typeof(DraggAnimatedPanel),
new FrameworkPropertyMetadata(150d)); new FrameworkPropertyMetadata(150d));
public static readonly DependencyProperty ItemsHeightProperty = public static readonly DependencyProperty ItemsHeightProperty =
DependencyProperty.Register( DependencyProperty.Register(
"ItemsHeight", "ItemsHeight",
typeof(double), typeof(double),
typeof(DraggAnimatedPanel), typeof(DraggAnimatedPanel),
new FrameworkPropertyMetadata(60d)); new FrameworkPropertyMetadata(60d));
public static readonly DependencyProperty ItemSeparationProperty = public static readonly DependencyProperty ItemSeparationProperty =
DependencyProperty.Register( DependencyProperty.Register(
"ItemSeparation", "ItemSeparation",
typeof(Thickness), typeof(Thickness),
typeof(DraggAnimatedPanel), typeof(DraggAnimatedPanel),
new FrameworkPropertyMetadata()); new FrameworkPropertyMetadata());
// Using a DependencyProperty as the backing store for AnimationMilliseconds. This enables animation, styling, binding, etc... // Using a DependencyProperty as the backing store for AnimationMilliseconds. This enables animation, styling, binding, etc...
public static readonly DependencyProperty AnimationMillisecondsProperty = public static readonly DependencyProperty AnimationMillisecondsProperty =
DependencyProperty.Register("AnimationMilliseconds", typeof(int), typeof(DraggAnimatedPanel), new FrameworkPropertyMetadata(200)); DependencyProperty.Register("AnimationMilliseconds", typeof(int), typeof(DraggAnimatedPanel), new FrameworkPropertyMetadata(200));
public static readonly DependencyProperty SwapCommandProperty = public static readonly DependencyProperty SwapCommandProperty =
DependencyProperty.Register( DependencyProperty.Register(
"SwapCommand", "SwapCommand",
typeof(ICommand), typeof(ICommand),
typeof(DraggAnimatedPanel), typeof(DraggAnimatedPanel),
new FrameworkPropertyMetadata(null)); new FrameworkPropertyMetadata(null));
#endregion #endregion
#region properties #region properties
public double ItemsWidth public double ItemsWidth
{ {
get { return (double)GetValue(ItemsWidthProperty); } get { return (double)GetValue(ItemsWidthProperty); }
set { SetValue(ItemsWidthProperty, value); } set { SetValue(ItemsWidthProperty, value); }
} }
public double ItemsHeight public double ItemsHeight
{ {
get { return (double)GetValue(ItemsHeightProperty); } get { return (double)GetValue(ItemsHeightProperty); }
set { SetValue(ItemsHeightProperty, value); } set { SetValue(ItemsHeightProperty, value); }
} }
public Thickness ItemSeparation public Thickness ItemSeparation
{ {
get { return (Thickness)this.GetValue(ItemSeparationProperty); } get { return (Thickness)this.GetValue(ItemSeparationProperty); }
set { this.SetValue(ItemSeparationProperty, value); } set { this.SetValue(ItemSeparationProperty, value); }
} }
public int AnimationMilliseconds public int AnimationMilliseconds
{ {
get { return (int)GetValue(AnimationMillisecondsProperty); } get { return (int)GetValue(AnimationMillisecondsProperty); }
set { SetValue(AnimationMillisecondsProperty, value); } set { SetValue(AnimationMillisecondsProperty, value); }
} }
private double itemContainterHeight private double itemContainterHeight
{ {
get { return ItemSeparation.Top + ItemsHeight + ItemSeparation.Bottom; } get { return ItemSeparation.Top + ItemsHeight + ItemSeparation.Bottom; }
} }
private double itemContainterWidth private double itemContainterWidth
{ {
get { return ItemSeparation.Left + ItemsWidth + ItemSeparation.Right; } get { return ItemSeparation.Left + ItemsWidth + ItemSeparation.Right; }
} }
public ICommand SwapCommand public ICommand SwapCommand
{ {
get { return (ICommand)GetValue(SwapCommandProperty); } get { return (ICommand)GetValue(SwapCommandProperty); }
set { SetValue(SwapCommandProperty, value); } set { SetValue(SwapCommandProperty, value); }
} }
#endregion #endregion
#region transformation things #region transformation things
private void AnimateAll() private void AnimateAll()
{ {
//Apply exactly the same algorithm, but instide of Arrange a call AnimateTo method //Apply exactly the same algorithm, but instide of Arrange a call AnimateTo method
double colPosition = 0; double colPosition = 0;
double rowPosition = 0; double rowPosition = 0;
foreach (UIElement child in Children) foreach (UIElement child in Children)
{ {
if (child != _draggedElement) if (child != _draggedElement)
AnimateTo(child, colPosition + ItemSeparation.Left, rowPosition + ItemSeparation.Top, _isNotFirstArrange ? AnimationMilliseconds : 0); AnimateTo(child, colPosition + ItemSeparation.Left, rowPosition + ItemSeparation.Top, _isNotFirstArrange ? AnimationMilliseconds : 0);
//drag will locate dragged element //drag will locate dragged element
colPosition += itemContainterWidth; colPosition += itemContainterWidth;
if (colPosition + 1 > _calculatedSize.Width) if (colPosition + 1 > _calculatedSize.Width)
{ {
colPosition = 0; colPosition = 0;
rowPosition += itemContainterHeight; rowPosition += itemContainterHeight;
} }
} }
} }
private void AnimateTo(UIElement child, double x, double y, int duration) private void AnimateTo(UIElement child, double x, double y, int duration)
{ {
TransformGroup group = (TransformGroup)child.RenderTransform; TransformGroup group = (TransformGroup)child.RenderTransform;
TranslateTransform trans = (TranslateTransform)group.Children.First((groupElement) => groupElement is TranslateTransform); TranslateTransform trans = (TranslateTransform)group.Children.First((groupElement) => groupElement is TranslateTransform);
trans.BeginAnimation(TranslateTransform.XProperty, MakeAnimation(x, duration)); trans.BeginAnimation(TranslateTransform.XProperty, MakeAnimation(x, duration));
trans.BeginAnimation(TranslateTransform.YProperty, MakeAnimation(y, duration)); trans.BeginAnimation(TranslateTransform.YProperty, MakeAnimation(y, duration));
} }
private DoubleAnimation MakeAnimation(double to, int duration) private DoubleAnimation MakeAnimation(double to, int duration)
{ {
DoubleAnimation anim = new DoubleAnimation(to, TimeSpan.FromMilliseconds(duration)); DoubleAnimation anim = new DoubleAnimation(to, TimeSpan.FromMilliseconds(duration));
anim.AccelerationRatio = 0.2; anim.AccelerationRatio = 0.2;
anim.DecelerationRatio = 0.7; anim.DecelerationRatio = 0.7;
return anim; return anim;
} }
#endregion #endregion
#region measure #region measure
protected override Size MeasureOverride(Size availableSize) protected override Size MeasureOverride(Size availableSize)
{ {
Size itemContainerSize = new Size(itemContainterWidth, itemContainterHeight); Size itemContainerSize = new Size(itemContainterWidth, itemContainterHeight);
int count = 0; //for not call it again int count = 0; //for not call it again
foreach (UIElement child in Children) foreach (UIElement child in Children)
{ {
child.Measure(itemContainerSize); child.Measure(itemContainerSize);
count++; count++;
} }
if (availableSize.Width < itemContainterWidth) if (availableSize.Width < itemContainterWidth)
_calculatedSize = new Size(itemContainterWidth, count * itemContainterHeight); //the size of nX1 _calculatedSize = new Size(itemContainterWidth, count * itemContainterHeight); //the size of nX1
else else
{ {
columns = (int)Math.Truncate(availableSize.Width / itemContainterWidth); columns = (int)Math.Truncate(availableSize.Width / itemContainterWidth);
rows = count / columns; rows = count / columns;
if (count % columns != 0) if (count % columns != 0)
rows++; rows++;
_calculatedSize = new Size(columns * itemContainterWidth, rows * itemContainterHeight); _calculatedSize = new Size(columns * itemContainterWidth, rows * itemContainterHeight);
} }
return _calculatedSize; return _calculatedSize;
} }
#endregion #endregion
#region arrange #region arrange
protected override Size ArrangeOverride(Size finalSize) protected override Size ArrangeOverride(Size finalSize)
{ {
Size _finalItemSize = new Size(ItemsWidth, ItemsHeight); Size _finalItemSize = new Size(ItemsWidth, ItemsHeight);
//if is animated then arrange elements to 0,0, and then put them on its location using the transform //if is animated then arrange elements to 0,0, and then put them on its location using the transform
foreach (UIElement child in InternalChildren) foreach (UIElement child in InternalChildren)
{ {
// If this is the first time we've seen this child, add our transforms // If this is the first time we've seen this child, add our transforms
if (child.RenderTransform as TransformGroup == null) if (child.RenderTransform as TransformGroup == null)
{ {
child.RenderTransformOrigin = new Point(0.5, 0.5); child.RenderTransformOrigin = new Point(0.5, 0.5);
TransformGroup group = new TransformGroup(); TransformGroup group = new TransformGroup();
child.RenderTransform = group; child.RenderTransform = group;
group.Children.Add(new TranslateTransform()); group.Children.Add(new TranslateTransform());
} }
//locate all children in 0,0 point//TODO: use infinity and then scale each element to items size //locate all children in 0,0 point//TODO: use infinity and then scale each element to items size
child.Arrange(new Rect(new Point(0, 0), _finalItemSize)); //when use transformations change to childs.DesireSize child.Arrange(new Rect(new Point(0, 0), _finalItemSize)); //when use transformations change to childs.DesireSize
} }
AnimateAll(); AnimateAll();
if (!_isNotFirstArrange) if (!_isNotFirstArrange)
_isNotFirstArrange = true; _isNotFirstArrange = true;
return _calculatedSize; return _calculatedSize;
} }
#endregion #endregion
#region Static #region Static
//this can be an extension method //this can be an extension method
public static DependencyObject GetParent(DependencyObject o, Func<DependencyObject, bool> matchFunction) public static DependencyObject GetParent(DependencyObject o, Func<DependencyObject, bool> matchFunction)
{ {
DependencyObject t = o; DependencyObject t = o;
do do
{ {
t = VisualTreeHelper.GetParent(t); t = VisualTreeHelper.GetParent(t);
} while (t != null && !matchFunction.Invoke(t)); } while (t != null && !matchFunction.Invoke(t));
return t; return t;
} }
#endregion #endregion
//TODO: Add IsEditing property //TODO: Add IsEditing property
//TODO: Add Scale transform to items for fill items area //TODO: Add Scale transform to items for fill items area
} }
} }

View File

@@ -85,6 +85,7 @@
</ApplicationDefinition> </ApplicationDefinition>
<Compile Include="Command\DelegateCommand.cs" /> <Compile Include="Command\DelegateCommand.cs" />
<Compile Include="Command\DelegateCommandBase.cs" /> <Compile Include="Command\DelegateCommandBase.cs" />
<Compile Include="Constant\AppConstant.cs" />
<Compile Include="Constant\DefaultConstant.cs" /> <Compile Include="Constant\DefaultConstant.cs" />
<Compile Include="Constant\SortType.cs" /> <Compile Include="Constant\SortType.cs" />
<Compile Include="DraggAnimatedPanel\DraggAnimatedPanel.cs" /> <Compile Include="DraggAnimatedPanel\DraggAnimatedPanel.cs" />
@@ -98,9 +99,8 @@
<Compile Include="Util\MouseUtilities.cs" /> <Compile Include="Util\MouseUtilities.cs" />
<Compile Include="Util\SystemIcon.cs" /> <Compile Include="Util\SystemIcon.cs" />
<Compile Include="ViewModel\AppConfig.cs" /> <Compile Include="ViewModel\AppConfig.cs" />
<Compile Include="ViewModel\DataInfos.cs" /> <Compile Include="ViewModel\AppData.cs" />
<Compile Include="ViewModel\MainModel.cs" /> <Compile Include="ViewModel\IconInfo.cs" />
<Compile Include="ViewModel\MainViewModel.cs" />
<Compile Include="ViewModel\MenuViewModel.cs" /> <Compile Include="ViewModel\MenuViewModel.cs" />
<Page Include="MainWindow.xaml"> <Page Include="MainWindow.xaml">
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>

View File

@@ -8,7 +8,7 @@
xmlns:util="clr-namespace:GeekDesk.Util" xmlns:util="clr-namespace:GeekDesk.Util"
xmlns:DraggAnimatedPanel="clr-namespace:DraggAnimatedPanel" x:Name="window" xmlns:DraggAnimatedPanel="clr-namespace:DraggAnimatedPanel" x:Name="window"
xmlns:hc="https://handyorg.github.io/handycontrol" xmlns:hc="https://handyorg.github.io/handycontrol"
Title="MainWindow" Height="450" Width="800"> Title="MainWindow" Height="500" Width="600">
<Window.Resources> <Window.Resources>
<Style x:Key="ListBoxStyle" BasedOn="{StaticResource ListBoxBaseStyle}" TargetType="ListBox"/> <Style x:Key="ListBoxStyle" BasedOn="{StaticResource ListBoxBaseStyle}" TargetType="ListBox"/>
@@ -143,7 +143,7 @@
</ListBox.ItemTemplate> </ListBox.ItemTemplate>
</ListBox>--> </ListBox>-->
<ListBox x:Name="menu" ItemsSource="{Binding}"> <ListBox x:Name="menus" ItemsSource="{Binding MenuList}">
<ListBox.Resources> <ListBox.Resources>
<ContextMenu x:Key="menuDialog" Width="200"> <ContextMenu x:Key="menuDialog" Width="200">
<MenuItem Header="新建菜单"/> <MenuItem Header="新建菜单"/>
@@ -165,7 +165,7 @@
<ListBox.ItemTemplate> <ListBox.ItemTemplate>
<DataTemplate> <DataTemplate>
<TextBlock Text="{Binding menu}" PreviewMouseLeftButtonDown="menuClick" /> <TextBlock Text="{Binding}" PreviewMouseLeftButtonDown="menuClick" />
</DataTemplate> </DataTemplate>
</ListBox.ItemTemplate> </ListBox.ItemTemplate>
</ListBox> </ListBox>
@@ -176,31 +176,29 @@
<!--右侧栏--> <!--右侧栏-->
<hc:Card AllowDrop="True" Drop="Wrap_Drop" Opacity="1" x:Name="rightCard" Grid.Row="1" Grid.Column="1" BorderThickness="1" Effect="{DynamicResource EffectShadow2}" Margin="5,5,5,5"> <hc:Card AllowDrop="True" Drop="Wrap_Drop" Opacity="1" x:Name="rightCard" Grid.Row="1" Grid.Column="1" BorderThickness="1" Effect="{DynamicResource EffectShadow2}" Margin="5,5,5,5">
<WrapPanel Orientation="Horizontal"> <WrapPanel Orientation="Horizontal">
<ListBox x:Name="data" ItemsSource="{Binding}" <ListBox x:Name="icons" ItemsSource="{Binding}"
BorderThickness="0" BorderThickness="0"
SelectionChanged="data_SelectionChanged" SelectionChanged="data_SelectionChanged"
> >
<!--<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource dataStyle}"/>
</ListBox.ItemContainerStyle>-->
<ListBox.ItemsPanel> <ListBox.ItemsPanel>
<ItemsPanelTemplate> <ItemsPanelTemplate>
<DraggAnimatedPanel:DraggAnimatedPanel ItemsHeight="115" ItemsWidth="100" HorizontalAlignment="Center" SwapCommand="{Binding SwapCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/> <DraggAnimatedPanel:DraggAnimatedPanel ItemsHeight="115" ItemsWidth="100" HorizontalAlignment="Center" SwapCommand="{Binding SwapCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>
</ItemsPanelTemplate> </ItemsPanelTemplate>
</ListBox.ItemsPanel> </ListBox.ItemsPanel>
<ListBox.ItemTemplate> <ListBox.ItemTemplate>
<DataTemplate> <DataTemplate>
<Border Margin="5,5,5,5" CornerRadius="10"> <Border Margin="5,5,5,5" CornerRadius="10">
<StackPanel Tag="{Binding Path}" <StackPanel Tag="{Binding}"
MouseLeftButtonDown="dataClick" MouseLeftButtonDown="dataClick"
HorizontalAlignment="Center" HorizontalAlignment="Center"
hc:Poptip.HitMode="None"
hc:Poptip.IsOpen="{Binding IsMouseOver, RelativeSource={RelativeSource Self}}"
hc:Poptip.Content="{Binding Path}"
hc:Poptip.Placement="BottomLeft"
Margin="5,5,5,5" Margin="5,5,5,5"
Height="115" Height="115"
hc:Poptip.HitMode="None"
hc:Poptip.IsOpen="{Binding IsMouseOver, RelativeSource={RelativeSource Self}}"
hc:Poptip.Content="{Binding Content}"
hc:Poptip.Placement="BottomLeft"
> >
<Image Style="{StaticResource imageStyle}"></Image> <Image Style="{StaticResource imageStyle}"></Image>
<TextBlock Width="80" TextWrapping="Wrap" TextAlignment="Center" Height="35" LineHeight="15" FontSize="12" Text="{Binding Name}"/> <TextBlock Width="80" TextWrapping="Wrap" TextAlignment="Center" Height="35" LineHeight="15" FontSize="12" Text="{Binding Name}"/>

View File

@@ -1,22 +1,15 @@
using System; using DraggAnimatedPanelExample;
using GalaSoft.MvvmLight;
using GeekDesk.Util;
using GeekDesk.ViewModel;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Windows; using System.Windows;
using System.Windows.Controls;
using System.Windows.Input; using System.Windows.Input;
using System.Windows.Media.Imaging; using System.Windows.Media.Imaging;
using GeekDesk.ViewModel;
using System.IO;
using GeekDesk.Util;
using GalaSoft.MvvmLight;
using System.Windows.Controls;
using System.Windows.Media;
using System.Collections.ObjectModel;
using WPF.JoshSmith.ServiceProviders.UI;
using DraggAnimatedPanelExample;
using System.ComponentModel;
namespace GeekDesk namespace GeekDesk
{ {
/// <summary> /// <summary>
@@ -25,15 +18,18 @@ namespace GeekDesk
/// ///
public partial class MainWindow : Window public partial class MainWindow : Window
{ {
private static MainModel mainModel;
ListViewDragDropManager<ViewModel.Menu> dragMgr; private static AppData appData = CommonCode.GetAppData();
ListViewDragDropManager<ViewModel.DataInfos> dragMgr2;
public MainWindow() public MainWindow()
{ {
InitializeComponent(); InitializeComponent();
loadData();
List<string> menuList = new List<string>();
Dictionary<string, List<IconInfo>> iconMap = new Dictionary<string, List<IconInfo>>();
mainModel = new MainModel();
//this.DataContext = mainModel; //this.DataContext = mainModel;
//menu.Items = mainModel; //menu.Items = mainModel;
//System.Diagnostics.Process.Start(@"D:\SoftWare\WeGame\wegame.exe"); //System.Diagnostics.Process.Start(@"D:\SoftWare\WeGame\wegame.exe");
@@ -41,6 +37,29 @@ namespace GeekDesk
this.SizeChanged += MainWindow_Resize; this.SizeChanged += MainWindow_Resize;
} }
private void loadData()
{
this.DataContext = appData;
appData.MenuList.Add("Test1");
this.Width = appData.AppConfig.WindowWidth;
this.Height = appData.AppConfig.WindowHeight;
List<IconInfo> iconList;
if (appData.IconMap.ContainsKey("1"))
{
iconList = appData.IconMap["1"];
}
else
{
iconList = new List<IconInfo>();
appData.IconMap.Add("1", iconList);
}
icons.ItemsSource = iconList;
}
DelegateCommand<int[]> _swap; DelegateCommand<int[]> _swap;
public DelegateCommand<int[]> SwapCommand public DelegateCommand<int[]> SwapCommand
{ {
@@ -52,17 +71,17 @@ namespace GeekDesk
{ {
int fromS = indexes[0]; int fromS = indexes[0];
int to = indexes[1]; int to = indexes[1];
var elementSource = data.Items[to]; var elementSource = icons.Items[to];
var dragged = data.Items[fromS]; var dragged = icons.Items[fromS];
if (fromS > to) if (fromS > to)
{ {
data.Items.Remove(dragged); icons.Items.Remove(dragged);
data.Items.Insert(to, dragged); icons.Items.Insert(to, dragged);
} }
else else
{ {
data.Items.Remove(dragged); icons.Items.Remove(dragged);
data.Items.Insert(to, dragged); icons.Items.Insert(to, dragged);
} }
} }
); );
@@ -80,17 +99,17 @@ namespace GeekDesk
{ {
int fromS = indexes[0]; int fromS = indexes[0];
int to = indexes[1]; int to = indexes[1];
var elementSource = menu.Items[to]; var elementSource = menus.Items[to];
var dragged = menu.Items[fromS]; var dragged = menus.Items[fromS];
if (fromS > to) if (fromS > to)
{ {
menu.Items.Remove(dragged); menus.Items.Remove(dragged);
menu.Items.Insert(to, dragged); menus.Items.Insert(to, dragged);
} }
else else
{ {
menu.Items.Remove(dragged); menus.Items.Remove(dragged);
menu.Items.Insert(to, dragged); menus.Items.Insert(to, dragged);
} }
} }
); );
@@ -104,23 +123,41 @@ namespace GeekDesk
{ {
Array dropObject = (System.Array)e.Data.GetData(DataFormats.FileDrop); Array dropObject = (System.Array)e.Data.GetData(DataFormats.FileDrop);
if (dropObject == null) return; if (dropObject == null) return;
string path = (string)dropObject.GetValue(0); foreach (object obj in dropObject)
if (File.Exists(path))
{ {
// 文件 string path = (string)obj;
BitmapImage bi = FileIcon.GetBitmapImage(path); if (File.Exists(path))
DataInfos infos = new DataInfos(); {
infos.Path = path; // 文件
infos.BitmapImage = bi; BitmapImage bi = FileIcon.GetBitmapImage(path);
infos.Name = Path.GetFileNameWithoutExtension(path); IconInfo iconInfo = new IconInfo();
data.Items.Add(infos); iconInfo.Path = path;
data.Items.Refresh(); iconInfo.BitmapImage = bi;
} iconInfo.Name = Path.GetFileNameWithoutExtension(path);
else if (Directory.Exists(path)) List<IconInfo> iconList;
{ if (appData.IconMap.ContainsKey("1"))
//文件夹 {
iconList = appData.IconMap["1"];
}
else
{
iconList = new List<IconInfo>();
appData.IconMap.Add("1", iconList);
}
iconList.Add(iconInfo);
icons.ItemsSource = iconList;
CommonCode.SaveAppData(appData);
}
else if (Directory.Exists(path))
{
//文件夹
}
} }
icons.Items.Refresh();
} }
@@ -139,8 +176,10 @@ namespace GeekDesk
/// <param name="e"></param> /// <param name="e"></param>
private void dataClick(object sender, MouseButtonEventArgs e) private void dataClick(object sender, MouseButtonEventArgs e)
{ {
//string path = ((StackPanel)sender).Tag.ToString(); IconInfo icon = (IconInfo)((StackPanel)sender).Tag;
//System.Diagnostics.Process.Start(path); System.Diagnostics.Process.Start(icon.Path);
icon.Count++;
CommonCode.SaveAppData(appData);
} }
/// <summary> /// <summary>
@@ -150,128 +189,42 @@ namespace GeekDesk
/// <param name="e"></param> /// <param name="e"></param>
private void data_SelectionChanged(object sender, SelectionChangedEventArgs e) private void data_SelectionChanged(object sender, SelectionChangedEventArgs e)
{ {
if (data.SelectedIndex != -1) data.SelectedIndex = -1; if (icons.SelectedIndex != -1) icons.SelectedIndex = -1;
} }
#region Window_Loaded #region Window_Loaded
void Window_Loaded(object sender, RoutedEventArgs e) void Window_Loaded(object sender, RoutedEventArgs e)
{ {
AppConfig config = CommonCode.GetAppConfig(); //this.menus.Items.Add(new ViewModel.Menu() { menu = "test1" });
this.Width = config.WindowWidth; //this.menus.Items.Add(new ViewModel.Menu() { menu = "test2" });
this.Height = config.WindowHeight; //this.menus.Items.Add(new ViewModel.Menu() { menu = "test3" });
this.DataContext = config;
this.menu.Items.Add(new ViewModel.Menu() { menu = "test1" });
this.menu.Items.Add(new ViewModel.Menu() { menu = "test2" });
this.menu.Items.Add(new ViewModel.Menu() { menu = "test3" });
} }
#endregion // Window_Loaded #endregion // Window_Loaded
#region Window_Closing //#region Window_Closing
void Window_Closing(object sender, CancelEventArgs e) //void Window_Closing(object sender, CancelEventArgs e)
{ //{
Rect rect = this.RestoreBounds; // Rect rect = this.RestoreBounds;
AppConfig config = this.DataContext as AppConfig; // AppConfig config = this.DataContext as AppConfig;
config.WindowWidth = rect.Width; // config.WindowWidth = rect.Width;
config.WindowHeight = rect.Height; // config.WindowHeight = rect.Height;
CommonCode.SaveAppConfig(config); // CommonCode.SaveAppConfig(config);
} //}
#endregion // Window_Closing //#endregion // Window_Closing
void MainWindow_Resize(object sender, System.EventArgs e) void MainWindow_Resize(object sender, System.EventArgs e)
{ {
if (this.DataContext != null) if (this.DataContext != null)
{ {
AppConfig config = this.DataContext as AppConfig; AppData appData = this.DataContext as AppData;
config.WindowWidth = this.Width; appData.AppConfig.WindowWidth = this.Width;
config.WindowHeight = this.Height; appData.AppConfig.WindowHeight = this.Height;
CommonCode.SaveAppConfig(config); CommonCode.SaveAppData(appData);
}
}
#region dragMgr_ProcessDrop
// Performs custom drop logic for the top ListView.
void dragMgr_ProcessDrop(object sender, ProcessDropEventArgs<object> e)
{
// This shows how to customize the behavior of a drop.
// Here we perform a swap, instead of just moving the dropped item.
int higherIdx = Math.Max(e.OldIndex, e.NewIndex);
int lowerIdx = Math.Min(e.OldIndex, e.NewIndex);
if (lowerIdx < 0)
{
// The item came from the lower ListView
// so just insert it.
e.ItemsSource.Insert(higherIdx, e.DataItem);
}
else
{
// null values will cause an error when calling Move.
// It looks like a bug in ObservableCollection to me.
if (e.ItemsSource[lowerIdx] == null ||
e.ItemsSource[higherIdx] == null)
return;
// The item came from the ListView into which
// it was dropped, so swap it with the item
// at the target index.
e.ItemsSource.Move(lowerIdx, higherIdx);
e.ItemsSource.Move(higherIdx - 1, lowerIdx);
}
// Set this to 'Move' so that the OnListViewDrop knows to
// remove the item from the other ListView.
e.Effects = DragDropEffects.Move;
}
#endregion // dragMgr_ProcessDrop
#region OnListViewDragEnter
// Handles the DragEnter event for both ListViews.
void OnListViewDragEnter(object sender, DragEventArgs e)
{
e.Effects = DragDropEffects.Move;
}
#endregion // OnListViewDragEnter
#region OnListViewDrop
// Handles the Drop event for both ListViews.
void OnListViewDrop(object sender, DragEventArgs e)
{
if (e.Effects == DragDropEffects.None)
return;
ViewModel.Menu menuV = e.Data.GetData(typeof(ViewModel.Menu)) as ViewModel.Menu;
DataInfos data = e.Data.GetData(typeof(DataInfos)) as DataInfos;
if (sender == this.menu)
{
if (this.dragMgr.IsDragInProgress)
return;
// An item was dragged from the bottom ListView into the top ListView
// so remove that item from the bottom ListView.
(this.data.ItemsSource as ObservableCollection<DataInfos>).Remove(data);
}
else
{
if (this.dragMgr2.IsDragInProgress)
return;
// An item was dragged from the top ListView into the bottom ListView
// so remove that item from the top ListView.
(this.menu.ItemsSource as ObservableCollection<ViewModel.Menu>).Remove(menuV);
} }
} }
#endregion // OnListViewDrop
private void leftCard_MouseRightButtonDown(object sender, MouseButtonEventArgs e) private void leftCard_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{ {
@@ -287,13 +240,13 @@ namespace GeekDesk
ViewModel.Menu pojo = (ViewModel.Menu)((ContextMenu)((MenuItem)sender).Parent).DataContext; ViewModel.Menu pojo = (ViewModel.Menu)((ContextMenu)((MenuItem)sender).Parent).DataContext;
string menuTitle = pojo.menu; string menuTitle = pojo.menu;
int index = 0; int index = 0;
foreach (object obj in menu.Items) foreach (object obj in menus.Items)
{ {
string test = ((ViewModel.Menu)obj).menu; string test = ((ViewModel.Menu)obj).menu;
if (test == menuTitle) if (test == menuTitle)
{ {
menu.Items.RemoveAt(index); menus.Items.RemoveAt(index);
menu.Items.Refresh(); menus.Items.Refresh();
return; return;
} }
index++; index++;
@@ -301,10 +254,7 @@ namespace GeekDesk
} }
public Double ConvertString(string val)
{
return Convert.ToDouble(val);
}
} }
@@ -315,7 +265,7 @@ namespace GeekDesk
{ {
public List<ViewModel.Menu> MenuList { get; set; } public List<ViewModel.Menu> MenuList { get; set; }
public List<ViewModel.DataInfos> DataList { get; set; } public List<ViewModel.IconInfo> DataList { get; set; }
} }

View File

@@ -1,6 +1,4 @@
using System.Reflection; using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Windows; using System.Windows;

View File

@@ -1,12 +1,7 @@
using Newtonsoft.Json; using GeekDesk.Constant;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using GeekDesk.ViewModel; using GeekDesk.ViewModel;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
/// <summary> /// <summary>
/// 提取一些代码 /// 提取一些代码
@@ -15,45 +10,49 @@ namespace GeekDesk.Util
{ {
class CommonCode class CommonCode
{ {
private static string appConfigFilePath = AppDomain.CurrentDomain.BaseDirectory.Trim() + "\\config";
/// <summary> /// <summary>
/// 获取app配置 /// 获取app 数据
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public static AppConfig GetAppConfig() public static AppData GetAppData()
{ {
AppConfig config; AppData appData;
if (!File.Exists(appConfigFilePath)) if (!File.Exists(AppConstant.DATA_FILE_PATH))
{ {
using (FileStream fs = File.Create(appConfigFilePath)) { } using (FileStream fs = File.Create(AppConstant.DATA_FILE_PATH)) { }
config = new AppConfig(); appData = new AppData();
SaveAppConfig(config); SaveAppData(appData);
} }
else else
{ {
using (FileStream fs = new FileStream(appConfigFilePath, FileMode.Open)) using (FileStream fs = new FileStream(AppConstant.DATA_FILE_PATH, FileMode.Open))
{ {
BinaryFormatter bf = new BinaryFormatter(); BinaryFormatter bf = new BinaryFormatter();
string json = bf.Deserialize(fs) as string; appData = bf.Deserialize(fs) as AppData;
config = JsonConvert.DeserializeObject<AppConfig>(json);
} }
} }
return config; return appData;
} }
/// <summary> /// <summary>
/// 保存app配置 /// 保存app 数据
/// </summary> /// </summary>
/// <param name="config"></param> /// <param name="appData"></param>
public static void SaveAppConfig(AppConfig config) public static void SaveAppData(AppData appData)
{ {
using (FileStream fs = new FileStream(appConfigFilePath, FileMode.Create))
using (FileStream fs = new FileStream(AppConstant.DATA_FILE_PATH, FileMode.Create))
{ {
BinaryFormatter bf = new BinaryFormatter(); BinaryFormatter bf = new BinaryFormatter();
string json = JsonConvert.SerializeObject(config); bf.Serialize(fs, appData);
bf.Serialize(fs, json);
} }
} }
} }
} }

View File

@@ -1,12 +1,8 @@
using System; using System;
using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Security; using System.Security;
using System.Text;
using System.Threading.Tasks;
namespace GeekDesk.Util namespace GeekDesk.Util
{ {

View File

@@ -1,175 +1,170 @@
// Copyright (C) Josh Smith - January 2007 // Copyright (C) Josh Smith - January 2007
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Documents;
using System.Windows; using System.Windows;
using System.Windows.Documents;
using System.Windows.Media; using System.Windows.Media;
using System.Windows.Shapes; using System.Windows.Shapes;
using System.Windows.Media.Animation;
using System.Windows.Controls;
namespace WPF.JoshSmith.Adorners namespace WPF.JoshSmith.Adorners
{ {
/// <summary> /// <summary>
/// Renders a visual which can follow the mouse cursor, /// Renders a visual which can follow the mouse cursor,
/// such as during a drag-and-drop operation. /// such as during a drag-and-drop operation.
/// </summary> /// </summary>
public class DragAdorner : Adorner public class DragAdorner : Adorner
{ {
#region Data #region Data
private Rectangle child = null; private Rectangle child = null;
private double offsetLeft = 0; private double offsetLeft = 0;
private double offsetTop = 0; private double offsetTop = 0;
#endregion // Data #endregion // Data
#region Constructor #region Constructor
/// <summary> /// <summary>
/// Initializes a new instance of DragVisualAdorner. /// Initializes a new instance of DragVisualAdorner.
/// </summary> /// </summary>
/// <param name="adornedElement">The element being adorned.</param> /// <param name="adornedElement">The element being adorned.</param>
/// <param name="size">The size of the adorner.</param> /// <param name="size">The size of the adorner.</param>
/// <param name="brush">A brush to with which to paint the adorner.</param> /// <param name="brush">A brush to with which to paint the adorner.</param>
public DragAdorner( UIElement adornedElement, Size size, Brush brush ) public DragAdorner(UIElement adornedElement, Size size, Brush brush)
: base( adornedElement ) : base(adornedElement)
{ {
Rectangle rect = new Rectangle(); Rectangle rect = new Rectangle();
rect.Fill = brush; rect.Fill = brush;
rect.Width = size.Width; rect.Width = size.Width;
rect.Height = size.Height; rect.Height = size.Height;
rect.IsHitTestVisible = false; rect.IsHitTestVisible = false;
this.child = rect; this.child = rect;
} }
#endregion // Constructor #endregion // Constructor
#region Public Interface #region Public Interface
#region GetDesiredTransform #region GetDesiredTransform
/// <summary> /// <summary>
/// Override. /// Override.
/// </summary> /// </summary>
/// <param name="transform"></param> /// <param name="transform"></param>
/// <returns></returns> /// <returns></returns>
public override GeneralTransform GetDesiredTransform( GeneralTransform transform ) public override GeneralTransform GetDesiredTransform(GeneralTransform transform)
{ {
GeneralTransformGroup result = new GeneralTransformGroup(); GeneralTransformGroup result = new GeneralTransformGroup();
result.Children.Add( base.GetDesiredTransform( transform ) ); result.Children.Add(base.GetDesiredTransform(transform));
result.Children.Add( new TranslateTransform( this.offsetLeft, this.offsetTop ) ); result.Children.Add(new TranslateTransform(this.offsetLeft, this.offsetTop));
return result; return result;
} }
#endregion // GetDesiredTransform #endregion // GetDesiredTransform
#region OffsetLeft #region OffsetLeft
/// <summary> /// <summary>
/// Gets/sets the horizontal offset of the adorner. /// Gets/sets the horizontal offset of the adorner.
/// </summary> /// </summary>
public double OffsetLeft public double OffsetLeft
{ {
get { return this.offsetLeft; } get { return this.offsetLeft; }
set set
{ {
this.offsetLeft = value; this.offsetLeft = value;
UpdateLocation(); UpdateLocation();
} }
} }
#endregion // OffsetLeft #endregion // OffsetLeft
#region SetOffsets #region SetOffsets
/// <summary> /// <summary>
/// Updates the location of the adorner in one atomic operation. /// Updates the location of the adorner in one atomic operation.
/// </summary> /// </summary>
/// <param name="left"></param> /// <param name="left"></param>
/// <param name="top"></param> /// <param name="top"></param>
public void SetOffsets( double left, double top ) public void SetOffsets(double left, double top)
{ {
this.offsetLeft = left; this.offsetLeft = left;
this.offsetTop = top; this.offsetTop = top;
this.UpdateLocation(); this.UpdateLocation();
} }
#endregion // SetOffsets #endregion // SetOffsets
#region OffsetTop #region OffsetTop
/// <summary> /// <summary>
/// Gets/sets the vertical offset of the adorner. /// Gets/sets the vertical offset of the adorner.
/// </summary> /// </summary>
public double OffsetTop public double OffsetTop
{ {
get { return this.offsetTop; } get { return this.offsetTop; }
set set
{ {
this.offsetTop = value; this.offsetTop = value;
UpdateLocation(); UpdateLocation();
} }
} }
#endregion // OffsetTop #endregion // OffsetTop
#endregion // Public Interface #endregion // Public Interface
#region Protected Overrides #region Protected Overrides
/// <summary> /// <summary>
/// Override. /// Override.
/// </summary> /// </summary>
/// <param name="constraint"></param> /// <param name="constraint"></param>
/// <returns></returns> /// <returns></returns>
protected override Size MeasureOverride( Size constraint ) protected override Size MeasureOverride(Size constraint)
{ {
this.child.Measure( constraint ); this.child.Measure(constraint);
return this.child.DesiredSize; return this.child.DesiredSize;
} }
/// <summary> /// <summary>
/// Override. /// Override.
/// </summary> /// </summary>
/// <param name="finalSize"></param> /// <param name="finalSize"></param>
/// <returns></returns> /// <returns></returns>
protected override Size ArrangeOverride( Size finalSize ) protected override Size ArrangeOverride(Size finalSize)
{ {
this.child.Arrange( new Rect( finalSize ) ); this.child.Arrange(new Rect(finalSize));
return finalSize; return finalSize;
} }
/// <summary> /// <summary>
/// Override. /// Override.
/// </summary> /// </summary>
/// <param name="index"></param> /// <param name="index"></param>
/// <returns></returns> /// <returns></returns>
protected override Visual GetVisualChild( int index ) protected override Visual GetVisualChild(int index)
{ {
return this.child; return this.child;
} }
/// <summary> /// <summary>
/// Override. Always returns 1. /// Override. Always returns 1.
/// </summary> /// </summary>
protected override int VisualChildrenCount protected override int VisualChildrenCount
{ {
get { return 1; } get { return 1; }
} }
#endregion // Protected Overrides #endregion // Protected Overrides
#region Private Helpers #region Private Helpers
private void UpdateLocation() private void UpdateLocation()
{ {
AdornerLayer adornerLayer = this.Parent as AdornerLayer; AdornerLayer adornerLayer = this.Parent as AdornerLayer;
if( adornerLayer != null ) if (adornerLayer != null)
adornerLayer.Update( this.AdornedElement ); adornerLayer.Update(this.AdornedElement);
} }
#endregion // Private Helpers #endregion // Private Helpers
} }
} }

View File

@@ -1,13 +1,7 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Drawing; using System.Drawing;
using System.Drawing.Imaging;
using System.IO; using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Media.Imaging; using System.Windows.Media.Imaging;
namespace GeekDesk.Util namespace GeekDesk.Util
@@ -46,12 +40,12 @@ namespace GeekDesk.Util
Bitmap bmp = ico.ToBitmap(); Bitmap bmp = ico.ToBitmap();
MemoryStream strm = new MemoryStream(); MemoryStream strm = new MemoryStream();
bmp.Save(strm, System.Drawing.Imaging.ImageFormat.Png); bmp.Save(strm, System.Drawing.Imaging.ImageFormat.Png);
BitmapImage bmpImage = new BitmapImage(); BitmapImage bmpImage = new BitmapImage();
bmpImage.BeginInit(); bmpImage.BeginInit();
strm.Seek(0, SeekOrigin.Begin); strm.Seek(0, SeekOrigin.Begin);
bmpImage.StreamSource = strm; bmpImage.StreamSource = strm;
bmpImage.EndInit(); bmpImage.EndInit();
return bmpImage.Clone(); return bmpImage.Clone();
} }

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +1,5 @@
using System; using System;
using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data; using System.Windows.Data;
namespace GeekDesk.Util namespace GeekDesk.Util
@@ -12,10 +8,11 @@ namespace GeekDesk.Util
{ {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{ {
if (value != null && value.ToString().Length>0) if (value != null && value.ToString().Length > 0)
{ {
return System.Convert.ToDouble(value.ToString()) - 10d; return System.Convert.ToDouble(value.ToString()) - 10d;
} else }
else
{ {
return 0d; return 0d;
} }

View File

@@ -1,58 +1,56 @@
using System; using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Windows; using System.Windows;
using System.Windows.Media; using System.Windows.Media;
namespace WPF.JoshSmith.Controls.Utilities namespace WPF.JoshSmith.Controls.Utilities
{ {
/// <summary> /// <summary>
/// Provides access to the mouse location by calling unmanaged code. /// Provides access to the mouse location by calling unmanaged code.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// This class was written by Dan Crevier (Microsoft). /// This class was written by Dan Crevier (Microsoft).
/// http://blogs.msdn.com/llobo/archive/2006/09/06/Scrolling-Scrollviewer-on-Mouse-Drag-at-the-boundaries.aspx /// http://blogs.msdn.com/llobo/archive/2006/09/06/Scrolling-Scrollviewer-on-Mouse-Drag-at-the-boundaries.aspx
/// </remarks> /// </remarks>
public class MouseUtilities public class MouseUtilities
{ {
[StructLayout( LayoutKind.Sequential )] [StructLayout(LayoutKind.Sequential)]
private struct Win32Point private struct Win32Point
{ {
public Int32 X; public Int32 X;
public Int32 Y; public Int32 Y;
}; };
[DllImport( "user32.dll" )] [DllImport("user32.dll")]
private static extern bool GetCursorPos( ref Win32Point pt ); private static extern bool GetCursorPos(ref Win32Point pt);
[DllImport( "user32.dll" )] [DllImport("user32.dll")]
private static extern bool ScreenToClient( IntPtr hwnd, ref Win32Point pt ); private static extern bool ScreenToClient(IntPtr hwnd, ref Win32Point pt);
/// <summary> /// <summary>
/// Returns the mouse cursor location. This method is necessary during /// Returns the mouse cursor location. This method is necessary during
/// a drag-drop operation because the WPF mechanisms for retrieving the /// a drag-drop operation because the WPF mechanisms for retrieving the
/// cursor coordinates are unreliable. /// cursor coordinates are unreliable.
/// </summary> /// </summary>
/// <param name="relativeTo">The Visual to which the mouse coordinates will be relative.</param> /// <param name="relativeTo">The Visual to which the mouse coordinates will be relative.</param>
public static Point GetMousePosition( Visual relativeTo ) public static Point GetMousePosition(Visual relativeTo)
{ {
Win32Point mouse = new Win32Point(); Win32Point mouse = new Win32Point();
GetCursorPos( ref mouse ); GetCursorPos(ref mouse);
// Using PointFromScreen instead of Dan Crevier's code (commented out below) // Using PointFromScreen instead of Dan Crevier's code (commented out below)
// is a bug fix created by William J. Roberts. Read his comments about the fix // is a bug fix created by William J. Roberts. Read his comments about the fix
// here: http://www.codeproject.com/useritems/ListViewDragDropManager.asp?msg=1911611#xx1911611xx // here: http://www.codeproject.com/useritems/ListViewDragDropManager.asp?msg=1911611#xx1911611xx
return relativeTo.PointFromScreen( new Point( (double)mouse.X, (double)mouse.Y ) ); return relativeTo.PointFromScreen(new Point((double)mouse.X, (double)mouse.Y));
#region Commented Out #region Commented Out
//System.Windows.Interop.HwndSource presentationSource = //System.Windows.Interop.HwndSource presentationSource =
// (System.Windows.Interop.HwndSource)PresentationSource.FromVisual( relativeTo ); // (System.Windows.Interop.HwndSource)PresentationSource.FromVisual( relativeTo );
//ScreenToClient( presentationSource.Handle, ref mouse ); //ScreenToClient( presentationSource.Handle, ref mouse );
//GeneralTransform transform = relativeTo.TransformToAncestor( presentationSource.RootVisual ); //GeneralTransform transform = relativeTo.TransformToAncestor( presentationSource.RootVisual );
//Point offset = transform.Transform( new Point( 0, 0 ) ); //Point offset = transform.Transform( new Point( 0, 0 ) );
//return new Point( mouse.X - offset.X, mouse.Y - offset.Y ); //return new Point( mouse.X - offset.X, mouse.Y - offset.Y );
#endregion // Commented Out #endregion // Commented Out
} }
} }
} }

View File

@@ -1,13 +1,6 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing; using System.Drawing;
using Microsoft.Win32;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Drawing.Imaging;
using GeekDesk.Util;
namespace GeekDesk.Util namespace GeekDesk.Util
{ {

View File

@@ -1,15 +1,13 @@
using GalaSoft.MvvmLight; 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GeekDesk.Constant; using GeekDesk.Constant;
using System;
using System.ComponentModel;
namespace GeekDesk.ViewModel namespace GeekDesk.ViewModel
{ {
[Serializable] [Serializable]
public class AppConfig : ViewModelBase public class AppConfig : System.ComponentModel.INotifyPropertyChanged
{ {
private int menuSortType = (int)SortType.CUSTOM; //菜单排序类型 private int menuSortType = (int)SortType.CUSTOM; //菜单排序类型
private int iconSortType = (int)SortType.CUSTOM; //图表排序类型 private int iconSortType = (int)SortType.CUSTOM; //图表排序类型
@@ -18,8 +16,10 @@ namespace GeekDesk.ViewModel
private double menuCardWidth = (double)DefaultConstant.MENU_CARD_WIDHT;//菜单栏宽度 private double menuCardWidth = (double)DefaultConstant.MENU_CARD_WIDHT;//菜单栏宽度
#region GetSet #region GetSet
public int MenuSortType { public int MenuSortType
{
get get
{ {
return menuSortType; return menuSortType;
@@ -27,7 +27,7 @@ namespace GeekDesk.ViewModel
set set
{ {
menuSortType = value; menuSortType = value;
RaisePropertyChanged(); OnPropertyChanged("MenuSortType");
} }
} }
@@ -40,7 +40,7 @@ namespace GeekDesk.ViewModel
set set
{ {
iconSortType = value; iconSortType = value;
RaisePropertyChanged(); OnPropertyChanged("IconSortType");
} }
} }
@@ -53,7 +53,7 @@ namespace GeekDesk.ViewModel
set set
{ {
windowWidth = value; windowWidth = value;
RaisePropertyChanged(); OnPropertyChanged("WindowWidth");
} }
} }
@@ -66,7 +66,7 @@ namespace GeekDesk.ViewModel
set set
{ {
windowHeight = value; windowHeight = value;
RaisePropertyChanged(); OnPropertyChanged("WindowHeight");
} }
} }
@@ -79,9 +79,17 @@ namespace GeekDesk.ViewModel
set set
{ {
menuCardWidth = value; menuCardWidth = value;
RaisePropertyChanged(); OnPropertyChanged("MenuCardWidth");
} }
} }
[field: NonSerializedAttribute()]
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion #endregion
} }

61
ViewModel/AppData.cs Normal file
View File

@@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace GeekDesk.ViewModel
{
[Serializable]
class AppData : INotifyPropertyChanged
{
private List<string> menuList = new List<string>();
private Dictionary<string, List<IconInfo>> iconMap = new Dictionary<string, List<IconInfo>>();
private AppConfig appConfig = new AppConfig();
public List<string> MenuList
{
get
{
return menuList;
}
set
{
menuList = value;
OnPropertyChanged("MenuList");
}
}
public Dictionary<string, List<IconInfo>> IconMap
{
get
{
return iconMap;
}
set
{
iconMap = value;
OnPropertyChanged("IconMap");
}
}
public AppConfig AppConfig
{
get
{
return appConfig;
}
set
{
appConfig = value;
OnPropertyChanged("AppConfig");
}
}
[field: NonSerializedAttribute()]
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}

View File

@@ -1,70 +0,0 @@
using GalaSoft.MvvmLight;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
namespace GeekDesk.ViewModel
{
public class DataInfos : ViewModelBase
{
private string path; //路径
private string name; //文件名
private int count = 0; //打开次数
private BitmapImage bitmapImage; //位图
public int Count
{
get
{
return count;
}
set
{
count = value;
RaisePropertyChanged();
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
RaisePropertyChanged();
}
}
public string Path
{
get
{
return path;
}
set
{
path = value;
RaisePropertyChanged();
}
}
public BitmapImage BitmapImage
{
get
{
return bitmapImage;
}
set
{
bitmapImage = value;
RaisePropertyChanged();
}
}
}
}

137
ViewModel/IconInfo.cs Normal file
View File

@@ -0,0 +1,137 @@
using System;
using System.ComponentModel;
using System.IO;
using System.Windows.Media.Imaging;
namespace GeekDesk.ViewModel
{
[Serializable]
public class IconInfo : INotifyPropertyChanged
{
private string path; //路径
private string name; //文件名
private int count = 0; //打开次数
[field: NonSerialized]
private BitmapImage bitmapImage; //位图
private byte[] imageByteArr; //图片 base64
private string content; //显示信息
public int Count
{
get
{
return count;
}
set
{
count = value;
Content = Path + "\n" + Name + "\n使用次数: " + Count;
OnPropertyChanged("Count");
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
Content = Path + "\n" + Name + "\n使用次数: " + Count;
OnPropertyChanged("Name");
}
}
public string Path
{
get
{
return path;
}
set
{
path = value;
Content = Path + "\n" + Name + "\n使用次数: " + Count;
OnPropertyChanged("Path");
}
}
public BitmapImage BitmapImage
{
get
{
return ToImage(ImageByteArr);
}
set
{
bitmapImage = value;
ImageByteArr = getJPGFromImageControl(bitmapImage);
OnPropertyChanged("BitmapImage");
}
}
public byte[] ImageByteArr
{
get
{
return imageByteArr;
}
set
{
imageByteArr = value;
OnPropertyChanged("ImageByteArr");
}
}
public string Content
{
get
{
return content;
}
set
{
content = value;
OnPropertyChanged("Content");
}
}
[field: NonSerializedAttribute()]
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public BitmapImage ToImage(byte[] array)
{
using (var ms = new System.IO.MemoryStream(array))
{
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad; // here
image.StreamSource = ms;
image.EndInit();
return image;
}
}
public byte[] getJPGFromImageControl(BitmapImage bi)
{
using (MemoryStream memStream = new MemoryStream())
{
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bi));
encoder.Save(memStream);
return memStream.GetBuffer();
}
}
}
}

View File

@@ -1,12 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GeekDesk.ViewModel
{
class MainModel
{
}
}

View File

@@ -1,34 +0,0 @@
using GalaSoft.MvvmLight;
namespace GeekDesk.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
{
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
////if (IsInDesignMode)
////{
//// // Code runs in Blend --> create design time data.
////}
////else
////{
//// // Code runs "for real"
////}
}
}
}

View File

@@ -1,9 +1,4 @@
using System; using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GeekDesk.ViewModel namespace GeekDesk.ViewModel
{ {
@@ -12,7 +7,7 @@ namespace GeekDesk.ViewModel
public MenuViewModel() public MenuViewModel()
{ {
} }
public ObservableCollection<Menu> GetMenus() public ObservableCollection<Menu> GetMenus()
@@ -23,7 +18,7 @@ namespace GeekDesk.ViewModel
menus.Add(new Menu() { menu = "test3" }); menus.Add(new Menu() { menu = "test3" });
return menus; return menus;
} }
} }