code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
using System;
namespace PropertyTools.Wpf
{
/// <summary>
/// The WidePropertyAttribute is used for wide properties.
/// Properties marked with [WideProperty] will have the label above the editor.
/// Properties marked with [WideProperty(false)] will have no label.
/// The editor will use the full width of the available area.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class WidePropertyAttribute : Attribute
{
public bool ShowHeader { get; set; }
public WidePropertyAttribute()
{
ShowHeader = true;
}
public WidePropertyAttribute(bool showHeader)
{
ShowHeader = showHeader;
}
}
}
| zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Attributes/WidePropertyAttribute.cs | C# | gpl3 | 758 |
using System;
namespace PropertyTools.Wpf
{
/// <summary>
/// The DirectoryPathAttribute is used for directory properties.
/// A "Browse" button will be added, and a FolderBrowser dialog will be used to edit the directory path.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class DirectoryPathAttribute : Attribute
{
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Attributes/DirectoryPathAttribute.cs | C# | gpl3 | 388 |
using System;
namespace PropertyTools.Wpf
{
/// <summary>
/// The FilePathAttribute is used for path properties.
/// The filter and default extension will be used by the open/save file dialogs.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class FilePathAttribute : Attribute
{
public FilePathAttribute(string filter, string defaultExt, bool useOpenDialog = true)
{
Filter = filter;
DefaultExtension = defaultExt;
UseOpenDialog = useOpenDialog;
}
public bool UseOpenDialog { get; set; }
public string Filter { get; set; }
public string DefaultExtension { get; set; }
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Attributes/FilePathAttribute.cs | C# | gpl3 | 730 |
using System;
namespace PropertyTools.Wpf
{
/// <summary>
/// The FormatStringAttribute is used to provide a format string for numeric properties.
/// Example usage:
/// [FormatString("0.00")]
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class FormatStringAttribute : Attribute
{
public static readonly OptionalAttribute Default;
public FormatStringAttribute()
{
FormatString = null;
}
public FormatStringAttribute(string fs)
{
FormatString = fs;
}
public string FormatString { get; set; }
public override bool Equals(object obj)
{
return FormatString.Equals((string)obj);
}
public override int GetHashCode()
{
return FormatString.GetHashCode();
}
public override bool IsDefaultAttribute()
{
return Equals(Default);
}
}
}
| zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Attributes/FormatStringAttribute.cs | C# | gpl3 | 1,029 |
using System;
namespace PropertyTools.Wpf
{
/// <summary>
/// The ResettableAttribute is used for resettable properties.
/// Properties marked with [Resettable] will have a reset button.
/// The button will reset the property to the configured reset value.
/// Example usage:
/// [Resettable] // Button label is "Reset"
/// [Resettable("Default")] // Button label is "Default"
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class ResettableAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref = "ResettableAttribute" /> class.
/// </summary>
public ResettableAttribute()
{
ButtonLabel = "Reset";
}
/// <summary>
/// Initializes a new instance of the <see cref = "ResettableAttribute" /> class.
/// </summary>
/// <param name = "label">The label.</param>
public ResettableAttribute(string label)
{
ButtonLabel = label;
}
public object ButtonLabel { get; set; }
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Attributes/ResettableAttribute.cs | C# | gpl3 | 1,175 |
using System;
namespace PropertyTools.Wpf
{
/// <summary>
/// The SortOrderAttribute is used to sort the tabs, categories and properties.
/// Example usage:
/// [SortOrder(100)]
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class SortOrderAttribute : Attribute
{
public SortOrderAttribute(int sortOrder)
{
SortOrder = sortOrder;
}
public int SortOrder { get; set; }
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Attributes/SortOrderAttribute.cs | C# | gpl3 | 493 |
using System;
namespace PropertyTools.Wpf
{
/// <summary>
/// The RadiobuttonAttribute defines if an enum property should use a
/// radiobutton list as its editor. If the UseRadioButtons property is false, a combobox will be used.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class RadioButtonsAttribute : Attribute
{
public bool UseRadioButtons { get; set; }
public RadioButtonsAttribute()
{
this.UseRadioButtons = true;
}
public RadioButtonsAttribute(bool useRadioButtons)
{
this.UseRadioButtons = useRadioButtons;
}
}
}
| zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Attributes/RadioButtonsAttribute.cs | C# | gpl3 | 696 |
using System.ComponentModel;
namespace PropertyTools.Wpf
{
public interface IPropertyViewModelFactory
{
/// <summary>
/// Create a PropertyViewModel for the given property.
/// The ViewModel could be populated with data from local attributes.
/// </summary>
/// <param name="instance"></param>
/// <param name="descriptor"></param>
/// <returns></returns>
PropertyViewModel CreateViewModel(object instance, PropertyDescriptor descriptor);
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Interfaces/IPropertyViewModelFactory.cs | C# | gpl3 | 537 |
using System;
using System.Windows.Media;
namespace PropertyTools.Wpf
{
/// <summary>
/// Provides images for PropertyEditor tab icons.
/// Used in PropertyEditor.ImageProvider
/// </summary>
public interface IImageProvider
{
/// <summary>
/// Return the image
/// </summary>
/// <param name="type">Type of the instance being edited</param>
/// <param name="key">Tab name/key</param>
/// <returns></returns>
ImageSource GetImage(Type type, string key);
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Interfaces/IImageProvider.cs | C# | gpl3 | 561 |
using System;
namespace PropertyTools.Wpf
{
/// <summary>
/// Localize tab/category/property names and tooltips.
/// Used in PropertyEditor.LocalizationService
/// </summary>
public interface ILocalizationService
{
string GetString(Type instanceType, string key);
object GetTooltip(Type instanceType, string key);
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Interfaces/ILocalizationService.cs | C# | gpl3 | 383 |
using System.ComponentModel;
namespace PropertyTools.Wpf
{
/// <summary>
/// Return Enabled, Visible, Error and Warning states for a given component and property.
/// </summary>
public interface IPropertyStateProvider
{
bool IsEnabled(object component, PropertyDescriptor descriptor);
bool IsVisible(object component, PropertyDescriptor descriptor);
string GetError(object component, PropertyDescriptor descriptor);
string GetWarning(object component, PropertyDescriptor descriptor);
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Interfaces/IPropertyStateProvider.cs | C# | gpl3 | 561 |
namespace PropertyTools.Wpf
{
public interface IResettableProperties
{
object GetResetValue(string propertyName);
}
}
| zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Interfaces/IResettableProperties.cs | C# | gpl3 | 145 |
using System;
using System.Collections.Generic;
namespace PropertyTools.Wpf
{
// todo: consider to solve this in other ways...
/// <summary>
/// Implement this interface on your model class to be able to updates the
/// property enabled/visible states of the properties.
/// This update method is called after every property change of the same instance.
/// </summary>
public interface IPropertyStateUpdater
{
void UpdatePropertyStates(PropertyStateBag stateBag);
}
public class PropertyStateBag
{
internal Dictionary<string, bool> EnabledProperties { get; private set; }
internal Dictionary<string, bool> VisibleProperties { get; private set; }
public PropertyStateBag()
{
EnabledProperties = new Dictionary<string, bool>();
VisibleProperties = new Dictionary<string, bool>();
}
public void Enable(string propertyName, bool enable)
{
EnabledProperties[propertyName] = enable;
//if (EnabledProperties.ContainsKey(propertyName))
// EnabledProperties[propertyName] = enable;
//EnabledProperties.Add(propertyName,enable);
}
public bool? IsEnabled(string propertyName)
{
if (EnabledProperties.ContainsKey(propertyName))
return EnabledProperties[propertyName];
return null;
}
}
}
| zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Interfaces/IPropertyStateUpdater.cs | C# | gpl3 | 1,493 |
using System;
using System.ComponentModel;
using System.Linq;
namespace PropertyTools.Wpf
{
public static class AttributeHelper
{
/// <summary>
/// Return the first attribute of a given type
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="descriptor"></param>
/// <returns></returns>
public static T GetFirstAttribute<T>(PropertyDescriptor descriptor) where T : Attribute
{
return descriptor.Attributes.OfType<T>().FirstOrDefault();
}
/// <summary>
/// Check if an attribute collection contains an attribute of the given type
/// </summary>
/// <param name="attributes"></param>
/// <param name="attributeType"></param>
/// <returns></returns>
public static bool ContainsAttributeOfType(AttributeCollection attributes, Type attributeType)
{
// return attributes.Cast<object>().Any(a => attributeType.IsAssignableFrom(a.GetType()));))))
foreach (object a in attributes)
if (attributeType.IsAssignableFrom(a.GetType()))
return true;
return false;
}
}
public class PropertyInfoHelper {
public static void SetProperty(object instance, string propertyName, object value)
{
var pi = instance.GetType().GetProperty(propertyName);
pi.SetValue(instance, value, null);
}
public static object GetProperty(object instance, string propertyName)
{
var pi = instance.GetType().GetProperty(propertyName);
return pi.GetValue(instance, null);
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Helpers/AttributeHelper.cs | C# | gpl3 | 1,753 |
using System;
using System.Globalization;
using System.Windows.Media;
namespace PropertyTools.Wpf
{
/// <summary>
/// Static <see cref="Color"/> helper methods.
/// </summary>
public static class ColorHelper
{
public static Color UndefinedColor = Color.FromArgb(0, 0, 0, 0);
/// <summary>
/// Change the alpha value of a color
/// </summary>
/// <param name="c"></param>
/// <param name="alpha"></param>
/// <returns></returns>
public static Color ChangeAlpha(Color c, byte alpha)
{
return Color.FromArgb(alpha, c.R, c.G, c.B);
}
/// <summary>
/// Linear interpolation between two <see cref="Color"/>s.
/// </summary>
/// <param name="c0"></param>
/// <param name="c1"></param>
/// <param name="x"></param>
/// <returns></returns>
public static Color Interpolate(Color c0, Color c1, double x)
{
double r = c0.R * (1 - x) + c1.R * x;
double g = c0.G * (1 - x) + c1.G * x;
double b = c0.B * (1 - x) + c1.B * x;
double a = c0.A * (1 - x) + c1.A * x;
return Color.FromArgb((byte)a, (byte)r, (byte)g, (byte)b);
}
/// <summary>
/// Convert a <see cref="Color"/> to a hexadecimal string.
/// </summary>
/// <param name="color"></param>
/// <returns></returns>
public static string ColorToHex(Color color)
{
return string.Format("#{0:X2}{1:X2}{2:X2}{3:X2}", color.A, color.R, color.G, color.B);
}
/// <summary>
/// Calculates the difference between two <see cref="Color"/>s
/// </summary>
/// <param name="c1"></param>
/// <param name="c2"></param>
/// <returns>L2-norm in RGBA space</returns>
public static double ColorDifference(Color c1, Color c2)
{
// http://en.wikipedia.org/wiki/Color_difference
// http://mathworld.wolfram.com/L2-Norm.html
double dr = (c1.R - c2.R) / 255.0;
double dg = (c1.G - c2.G) / 255.0;
double db = (c1.B - c2.B) / 255.0;
double da = (c1.A - c2.A) / 255.0;
double e = dr * dr + dg * dg + db * db + da * da;
return Math.Sqrt(e);
}
/// <summary>
/// Calculate the difference in hue between two <see cref="Color"/>s.
/// </summary>
/// <param name="c1"></param>
/// <param name="c2"></param>
/// <returns></returns>
public static double HueDifference(Color c1, Color c2)
{
double[] hsv1 = ColorToHsv(c1);
double[] hsv2 = ColorToHsv(c2);
double dh = hsv1[0] - hsv2[0];
// clamp to [-0.5,0.5]
if (dh > 0.5) dh -= 1.0;
if (dh < -0.5) dh += 1.0;
double e = dh * dh;
return Math.Sqrt(e);
}
/// <summary>
/// Calculates the complementary color
/// </summary>
/// <param name="c"></param>
/// <returns></returns>
public static Color Complementary(Color c)
{
// http://en.wikipedia.org/wiki/Complementary_color
double[] hsv = ColorToHsv(c);
double newHue = hsv[0] - 0.5;
// clamp to [0,1]
if (newHue < 0) newHue += 1.0;
return HsvToColor(newHue, hsv[1], hsv[2]);
}
/// <summary>
/// Convert a hexadecimal string to <see cref="Color"/>.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static Color HexToColor(string value)
{
value = value.Trim('#');
if (value.Length == 0)
return UndefinedColor;
if (value.Length <= 6)
value = "FF" + value.PadLeft(6,'0');
uint u;
if (uint.TryParse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out u))
return UIntToColor(u);
return UndefinedColor;
}
/// <summary>
/// Convert an unsigned int (32bit) to <see cref="Color"/>
/// </summary>
/// <param name="color"></param>
/// <returns></returns>
public static Color UIntToColor(UInt32 color)
{
var a = (byte)(color >> 24);
var r = (byte)(color >> 16);
var g = (byte)(color >> 8);
var b = (byte)(color >> 0);
return Color.FromArgb(a, r, g, b);
}
/// <summary>
/// Convert a <see cref="Color"/> to unsigned int
/// </summary>
/// <param name="c"></param>
/// <returns></returns>
public static UInt32 ColorToUint(Color c)
{
UInt32 u = (UInt32)c.A << 24;
u += (UInt32)c.R << 16;
u += (UInt32)c.G << 8;
u += c.B;
return u;
//(UInt32)((UInt32)c.A << 24 + (UInt32)c.R << 16 + (UInt32)c.G << 8 + (UInt32)c.B);
}
/// <summary>
/// Converts from a <see cref="Color"/> to HSV values (byte)
/// </summary>
/// <param name="color"></param>
/// <returns>Array of [Hue,Saturation,Value] in the range [0,255]</returns>
public static byte[] ColorToHsvBytes(Color color)
{
double[] hsv1 = ColorToHsv(color);
var hsv2 = new byte[3];
hsv2[0] = (byte)(hsv1[0] * 255);
hsv2[1] = (byte)(hsv1[1] * 255);
hsv2[2] = (byte)(hsv1[2] * 255);
return hsv2;
}
/// <summary>
/// Converts from a <see cref="Color"/> to HSV values (double)
/// </summary>
/// <param name="color"></param>
/// <returns>Array of [Hue,Saturation,Value] in the range [0,1]</returns>
public static double[] ColorToHsv(Color color)
{
byte r = color.R;
byte g = color.G;
byte b = color.B;
double h = 0, s, v;
double min = Math.Min(Math.Min(r, g), b);
v = Math.Max(Math.Max(r, g), b);
double delta = v - min;
if (v == 0.0)
{
s = 0;
}
else
s = delta / v;
if (s == 0)
h = 0.0;
else
{
if (r == v)
h = (g - b) / delta;
else if (g == v)
h = 2 + (b - r) / delta;
else if (b == v)
h = 4 + (r - g) / delta;
h *= 60;
if (h < 0.0)
h = h + 360;
}
var hsv = new double[3];
hsv[0] = h / 360.0;
hsv[1] = s;
hsv[2] = v / 255.0;
return hsv;
}
/// <summary>
/// Converts from HSV to a RGB <see cref="Color"/>
/// </summary>
/// <param name="hue"></param>
/// <param name="saturation"></param>
/// <param name="value"></param>
/// <returns></returns>
public static Color HsvToColor(byte hue, byte saturation, byte value)
{
double r, g, b;
double h = hue * 360.0 / 255;
double s = saturation / 255.0;
double v = value / 255.0;
if (s == 0)
{
r = v;
g = v;
b = v;
}
else
{
int i;
double f, p, q, t;
if (h == 360)
h = 0;
else
h = h / 60;
i = (int)Math.Truncate(h);
f = h - i;
p = v * (1.0 - s);
q = v * (1.0 - (s * f));
t = v * (1.0 - (s * (1.0 - f)));
switch (i)
{
case 0:
r = v;
g = t;
b = p;
break;
case 1:
r = q;
g = v;
b = p;
break;
case 2:
r = p;
g = v;
b = t;
break;
case 3:
r = p;
g = q;
b = v;
break;
case 4:
r = t;
g = p;
b = v;
break;
default:
r = v;
g = p;
b = q;
break;
}
}
return Color.FromArgb(255, (byte)(r * 255), (byte)(g * 255), (byte)(b * 255));
}
/// <summary>
/// Convert from HSV to <see cref="Color"/>
/// http://en.wikipedia.org/wiki/HSL_color_space
/// </summary>
/// <param name="hue">Hue [0,1]</param>
/// <param name="sat">Saturation [0,1]</param>
/// <param name="val">Value [0,1]</param>
/// <returns></returns>
public static Color HsvToColor(double hue, double sat, double val)
{
int i;
double aa, bb, cc, f;
double r, g, b;
r = g = b = 0;
if (sat == 0) // Gray scale
r = g = b = val;
else
{
if (hue == 1.0) hue = 0;
hue *= 6.0;
i = (int)Math.Floor(hue);
f = hue - i;
aa = val * (1 - sat);
bb = val * (1 - (sat * f));
cc = val * (1 - (sat * (1 - f)));
switch (i)
{
case 0:
r = val;
g = cc;
b = aa;
break;
case 1:
r = bb;
g = val;
b = aa;
break;
case 2:
r = aa;
g = val;
b = cc;
break;
case 3:
r = aa;
g = bb;
b = val;
break;
case 4:
r = cc;
g = aa;
b = val;
break;
case 5:
r = val;
g = aa;
b = bb;
break;
}
}
return Color.FromRgb((byte)(r * 255), (byte)(g * 255), (byte)(b * 255));
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Helpers/ColorHelper.cs | C# | gpl3 | 11,429 |
namespace PropertyTools.Wpf
{
using System;
using System.Text.RegularExpressions;
/// <summary>
/// Formats the TimeSpan to a string
/// </summary>
/// <remarks>
/// http://www.java2s.com/Open-Source/CSharp/Sound-Mp3/stamp/Microsoft/Office/PowerPoint/STAMP/Core/TimeSpanFormatter.cs.htm
/// </remarks>
public class TimeSpanFormatter : IFormatProvider, ICustomFormatter
{
private readonly Regex formatParser;
/// <summary>
/// Initializes a new instance of the <see cref="TimeSpanFormatter"/> class.
/// </summary>
public TimeSpanFormatter()
{
this.formatParser = new Regex("D{1,2}|H{1,2}|M{1,2}|S{1,2}|d{1,2}|h{1,2}|m{1,2}|s{1,2}|f{1,7}", RegexOptions.Compiled);
}
#region IFormatProvider Members
/// <summary>
/// Returns an object that provides formatting services for the specified type.
/// </summary>
/// <param name="formatType">An object that specifies the type of format object to return.</param>
/// <returns>
/// An instance of the object specified by <paramref name="formatType"/>, if the <see cref="T:System.IFormatProvider"/> implementation can supply that type of object; otherwise, null.
/// </returns>
public object GetFormat(Type formatType)
{
if (typeof(ICustomFormatter).Equals(formatType))
{
return this;
}
return null;
}
#endregion
#region ICustomFormatter Members
/// <summary>
/// Converts the value of a specified timespan to an equivalent string representation using specified format and culture-specific formatting information.
/// </summary>
/// <param name="format">A format string containing formatting specifications.</param>
/// <param name="arg">An object to format.</param>
/// <param name="formatProvider">An object that supplies format information about the current instance.</param>
/// <returns>
/// The string representation of the value of <paramref name="arg"/>, formatted as specified by <paramref name="format"/> and <paramref name="formatProvider"/>.
/// </returns>
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (arg is TimeSpan)
{
var timeSpan = (TimeSpan)arg;
return this.formatParser.Replace(format, GetMatchEvaluator(timeSpan));
}
else
{
var formattable = arg as IFormattable;
if (formattable != null)
{
return formattable.ToString(format, formatProvider);
}
return arg != null ? arg.ToString() : string.Empty;
}
}
#endregion
private MatchEvaluator GetMatchEvaluator(TimeSpan timeSpan)
{
return m => EvaluateMatch(m, timeSpan);
}
private string EvaluateMatch(Match match, TimeSpan timeSpan)
{
switch (match.Value)
{
case "DD":
return timeSpan.TotalDays.ToString("00");
case "D":
return timeSpan.TotalDays.ToString("0");
case "dd":
return timeSpan.Days.ToString("00");
case "d":
return timeSpan.Days.ToString("0");
case "HH":
return ((int)timeSpan.TotalHours).ToString("00");
case "H":
return ((int)timeSpan.TotalHours).ToString("0");
case "hh":
return timeSpan.Hours.ToString("00");
case "h":
return timeSpan.Hours.ToString("0");
case "MM":
return ((int)timeSpan.TotalMinutes).ToString("00");
case "M":
return ((int)timeSpan.TotalMinutes).ToString("0");
case "mm":
return timeSpan.Minutes.ToString("00");
case "m":
return timeSpan.Minutes.ToString("0");
case "SS":
return ((int)timeSpan.TotalSeconds).ToString("00");
case "S":
return ((int)timeSpan.TotalSeconds).ToString("0");
case "ss":
return timeSpan.Seconds.ToString("00");
case "s":
return timeSpan.Seconds.ToString("0");
case "fffffff":
return (timeSpan.Milliseconds * 10000).ToString("0000000");
case "ffffff":
return (timeSpan.Milliseconds * 1000).ToString("000000");
case "fffff":
return (timeSpan.Milliseconds * 100).ToString("00000");
case "ffff":
return (timeSpan.Milliseconds * 10).ToString("0000");
case "fff":
return (timeSpan.Milliseconds).ToString("000");
case "ff":
return (timeSpan.Milliseconds / 10).ToString("00");
case "f":
return (timeSpan.Milliseconds / 100).ToString("0");
default:
return match.Value;
}
}
}
}
| zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Helpers/TimeSpanFormatter.cs | C# | gpl3 | 5,572 |
namespace PropertyTools.Wpf
{
using System;
using System.Globalization;
using System.Text.RegularExpressions;
/// <summary>
/// Parses a string to a TimeSpan.
/// </summary>
public class TimeSpanParser
{
private static readonly Regex parserExpression = new Regex(@"([0-9]*[,|.]?[0-9]*)\s*([d|h|m|s|'|""]?)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
/// <summary>
/// Parses the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="formatString">The format string.</param>
/// <returns>A TimeSpan.</returns>
public static TimeSpan Parse(string value, string formatString = null)
{
// todo: parse the formatstring and evaluate the timespan
// Examples
// FormatString = MM:ss, value = "91:12" => 91 minutes 12seconds
// FormatString = HH:mm, value = "91:12" => 91 hours 12minutes
if (value.Contains(":"))
return TimeSpan.Parse(value, CultureInfo.InvariantCulture);
// otherwise support values as:
// "12d"
// "12d 5h"
// "5m 3s"
// "12.5d"
TimeSpan total = new TimeSpan();
foreach (Match m in parserExpression.Matches(value))
{
string number = m.Groups[1].Value;
if (string.IsNullOrWhiteSpace(number))
continue;
double d = double.Parse(number.Replace(',', '.'), CultureInfo.InvariantCulture);
string unit = m.Groups[2].Value;
switch (unit.ToLower())
{
case "":
case "d":
total = total.Add(TimeSpan.FromDays(d));
break;
case "h":
total = total.Add(TimeSpan.FromHours(d));
break;
case "m":
case "'":
total = total.Add(TimeSpan.FromMinutes(d));
break;
case "\"":
case "s":
total = total.Add(TimeSpan.FromSeconds(d));
break;
}
}
return total;
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Helpers/TimeSpanParser.cs | C# | gpl3 | 2,437 |
using System;
using System.Collections;
namespace PropertyTools.Wpf
{
public static class TypeHelper
{
/// <summary>
/// Finds the biggest common type of items in the list.
/// </summary>
/// <param name="list">The list.</param>
/// <returns></returns>
public static Type FindBiggestCommonType(IEnumerable list)
{
Type type = null;
foreach (object item in list)
{
Type itemType = item.GetType();
if (type == null)
{
type = itemType;
continue;
}
while (type.BaseType != null && !type.IsAssignableFrom(itemType))
{
type = type.BaseType;
}
}
return type;
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Helpers/TypeHelper.cs | C# | gpl3 | 902 |
using System.Windows;
using System.Windows.Controls;
namespace PropertyTools.Wpf.Helpers
{
// from http://www.wpftutorial.net/PasswordBox.html
public static class PasswordHelper
{
public static readonly DependencyProperty PasswordProperty =
DependencyProperty.RegisterAttached("Password",
typeof (string), typeof (PasswordHelper),
new FrameworkPropertyMetadata(string.Empty, OnPasswordPropertyChanged));
public static readonly DependencyProperty AttachProperty =
DependencyProperty.RegisterAttached("Attach",
typeof (bool), typeof (PasswordHelper),
new PropertyMetadata(false, Attach));
private static readonly DependencyProperty IsUpdatingProperty =
DependencyProperty.RegisterAttached("IsUpdating", typeof (bool),
typeof (PasswordHelper));
public static void SetAttach(DependencyObject dp, bool value)
{
dp.SetValue(AttachProperty, value);
}
public static bool GetAttach(DependencyObject dp)
{
return (bool) dp.GetValue(AttachProperty);
}
public static string GetPassword(DependencyObject dp)
{
return (string) dp.GetValue(PasswordProperty);
}
public static void SetPassword(DependencyObject dp, string value)
{
dp.SetValue(PasswordProperty, value);
}
private static bool GetIsUpdating(DependencyObject dp)
{
return (bool) dp.GetValue(IsUpdatingProperty);
}
private static void SetIsUpdating(DependencyObject dp, bool value)
{
dp.SetValue(IsUpdatingProperty, value);
}
private static void OnPasswordPropertyChanged(DependencyObject sender,
DependencyPropertyChangedEventArgs e)
{
var passwordBox = sender as PasswordBox;
passwordBox.PasswordChanged -= PasswordChanged;
if (!GetIsUpdating(passwordBox))
{
passwordBox.Password = (string) e.NewValue;
}
passwordBox.PasswordChanged += PasswordChanged;
}
private static void Attach(DependencyObject sender,
DependencyPropertyChangedEventArgs e)
{
var passwordBox = sender as PasswordBox;
if (passwordBox == null)
return;
if ((bool) e.OldValue)
{
passwordBox.PasswordChanged -= PasswordChanged;
}
if ((bool) e.NewValue)
{
passwordBox.PasswordChanged += PasswordChanged;
}
}
private static void PasswordChanged(object sender, RoutedEventArgs e)
{
var passwordBox = sender as PasswordBox;
SetIsUpdating(passwordBox, true);
SetPassword(passwordBox, passwordBox.Password);
SetIsUpdating(passwordBox, false);
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Helpers/PasswordHelper.cs | C# | gpl3 | 3,343 |
using System.Windows;
using System.Windows.Controls;
namespace PropertyTools.Wpf
{
public class PopupBox : ComboBox
{
static PopupBox()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(PopupBox), new FrameworkPropertyMetadata(typeof(PopupBox)));
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
}
public DataTemplate PopupTemplate
{
get { return (DataTemplate)GetValue(PopupTemplateProperty); }
set { SetValue(PopupTemplateProperty, value); }
}
public static readonly DependencyProperty PopupTemplateProperty =
DependencyProperty.Register("PopupTemplate", typeof(DataTemplate), typeof(PopupBox), new UIPropertyMetadata(null));
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Controls/PopupBox/PopupBox.cs | C# | gpl3 | 838 |
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace PropertyTools.Wpf
{
/// <summary>
/// TextBox that updates the binding when Enter is pressed. Also moves focus to the next control.
/// Todo: replace by behaviour or attached dependency property?
/// </summary>
public class TextBoxEx : TextBox
{
public bool UpdateBindingOnEnter
{
get { return (bool)GetValue(UpdateBindingOnEnterProperty); }
set { SetValue(UpdateBindingOnEnterProperty, value); }
}
public static readonly DependencyProperty UpdateBindingOnEnterProperty =
DependencyProperty.Register("UpdateBindingOnEnter", typeof(bool), typeof(TextBoxEx), new UIPropertyMetadata(true));
public bool MoveFocusOnEnter
{
get { return (bool)GetValue(MoveFocusOnEnterProperty); }
set { SetValue(MoveFocusOnEnterProperty, value); }
}
public static readonly DependencyProperty MoveFocusOnEnterProperty =
DependencyProperty.Register("MoveFocusOnEnter", typeof(bool), typeof(TextBoxEx), new UIPropertyMetadata(true));
protected override void OnPreviewKeyDown(KeyEventArgs e)
{
base.OnPreviewKeyDown(e);
if (e.Key == Key.Enter && !AcceptsReturn)
{
if (UpdateBindingOnEnter)
{
// update binding
var b = GetBindingExpression(TextProperty);
if (b != null)
{
b.UpdateSource();
b.UpdateTarget();
}
}
if (MoveFocusOnEnter)
{
// Move focus to next element
// http://madprops.org/blog/enter-to-tab-in-wpf/
var uie = e.OriginalSource as UIElement;
if (uie != null)
uie.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
}
}
}
/* Microsoft.Expression.Interactivity
public class UpdateOnEnterBehavior : Behavior<TextBox>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.OnPreviewKeyDown += PreviewKeyDown;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.OnPreviewKeyDown -= PreviewKeyDown;
}
private void PreviewKeyDown(object sender,
System.Windows.Input.KeyboardFocusChangedEventArgs e)
{
if (e.Key == Key.Enter && !AcceptsReturn)
{
// update binding
var b = AssociatedObject.GetBindingExpression(TextBox.TextProperty);
if (b != null)
{
b.UpdateSource();
b.UpdateTarget();
}
}
}
}*/
}
| zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Controls/TextBoxEx.cs | C# | gpl3 | 3,149 |
using System.ComponentModel;
using System.Windows.Controls;
namespace PropertyTools.Wpf
{
/// <summary>
/// Slider that calls IEditableObject.BeginEdit/EndEdit when thumb dragging.
/// </summary>
public class SliderEx : Slider
{
protected override void OnThumbDragStarted(System.Windows.Controls.Primitives.DragStartedEventArgs e)
{
base.OnThumbDragStarted(e);
var editableObject = DataContext as IEditableObject;
if (editableObject != null)
{
editableObject.BeginEdit();
}
}
protected override void OnThumbDragCompleted(System.Windows.Controls.Primitives.DragCompletedEventArgs e)
{
base.OnThumbDragCompleted(e);
var editableObject = DataContext as IEditableObject;
if (editableObject != null)
{
editableObject.EndEdit();
}
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Controls/SliderEx.cs | C# | gpl3 | 989 |
using System;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
namespace PropertyTools.Wpf
{
/// <summary>
/// A TextBox with a bindable StringFormat property.
/// </summary>
public class FormattingTextBox : TextBox
{
public static readonly DependencyProperty FormatProviderProperty =
DependencyProperty.Register("FormatProvider", typeof(IFormatProvider), typeof(FormattingTextBox),
new UIPropertyMetadata(CultureInfo.InvariantCulture));
public static readonly DependencyProperty StringFormatProperty =
DependencyProperty.Register("StringFormat", typeof(string), typeof(FormattingTextBox),
new UIPropertyMetadata(null, StringFormatChanged));
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(object), typeof(FormattingTextBox),
new FrameworkPropertyMetadata(null,
FrameworkPropertyMetadataOptions.
BindsTwoWayByDefault, ValueChangedCallback));
private bool userIsChanging = true;
static FormattingTextBox()
{
// DefaultStyleKeyProperty.OverrideMetadata(typeof(FormattingTextBox), new FrameworkPropertyMetadata(typeof(FormattingTextBox)));
TextProperty.OverrideMetadata(typeof(FormattingTextBox), new FrameworkPropertyMetadata(TextChangedCallback));
}
public IFormatProvider FormatProvider
{
get { return (IFormatProvider)GetValue(FormatProviderProperty); }
set { SetValue(FormatProviderProperty, value); }
}
public string StringFormat
{
get { return (string)GetValue(StringFormatProperty); }
set { SetValue(StringFormatProperty, value); }
}
public object Value
{
get { return GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
private static void StringFormatChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((FormattingTextBox)d).UpdateText();
}
private void UpdateText()
{
userIsChanging = false;
string f = StringFormat;
if (f != null)
{
if (!f.Contains("{0"))
f = string.Format("{{0:{0}}}", f);
Text = String.Format(FormatProvider, f, Value);
}
else
{
Text = Value != null ? String.Format(FormatProvider, "{0}", Value) : null;
}
userIsChanging = true;
}
private string UnFormat(string s)
{
if (StringFormat == null)
return s;
var r = new Regex(@"(.*)(\{0.*\})(.*)");
var match = r.Match(StringFormat);
if (!match.Success)
return s;
if (match.Groups.Count > 1 && !String.IsNullOrEmpty(match.Groups[1].Value))
s = s.Replace(match.Groups[1].Value, "");
if (match.Groups.Count > 3 && !String.IsNullOrEmpty(match.Groups[3].Value))
s = s.Replace(match.Groups[3].Value, "");
return s;
}
private void UpdateValue()
{
if (userIsChanging)
Value = UnFormat(Text);
}
private static void ValueChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var ftb = (FormattingTextBox)d;
if (ftb.userIsChanging)
ftb.UpdateText();
}
private static void TextChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var ftb = (FormattingTextBox)d;
// if (ftb.userIsChanging)
ftb.UpdateValue();
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Controls/FormattingTextBox.cs | C# | gpl3 | 4,239 |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DirectoryPicker.cs" company="">
//
// </copyright>
// <summary>
// DirectoryPicker control
// </summary>
// --------------------------------------------------------------------------------------------------------------------
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using PropertyTools.Wpf.Shell32;
namespace PropertyTools.Wpf
{
/// <summary>
/// DirectoryPicker control
/// </summary>
public class DirectoryPicker : Control
{
/// <summary>
/// The directory property.
/// </summary>
public static readonly DependencyProperty DirectoryProperty =
DependencyProperty.Register("Directory", typeof (string), typeof (DirectoryPicker),
new FrameworkPropertyMetadata(null,
FrameworkPropertyMetadataOptions.
BindsTwoWayByDefault));
/// <summary>
/// Initializes static members of the <see cref="DirectoryPicker"/> class.
/// </summary>
static DirectoryPicker()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof (DirectoryPicker),
new FrameworkPropertyMetadata(typeof (DirectoryPicker)));
}
/// <summary>
/// Initializes a new instance of the <see cref="DirectoryPicker"/> class.
/// </summary>
public DirectoryPicker()
{
BrowseCommand = new DelegateCommand(Browse);
}
/// <summary>
/// Gets or sets Directory.
/// </summary>
public string Directory
{
get { return (string) GetValue(DirectoryProperty); }
set { SetValue(DirectoryProperty, value); }
}
/// <summary>
/// Gets or sets BrowseCommand.
/// </summary>
public ICommand BrowseCommand { get; set; }
public IFolderBrowserDialogService FolderBrowserDialogService
{
get { return (IFolderBrowserDialogService)GetValue(FolderBrowserDialogServiceProperty); }
set { SetValue(FolderBrowserDialogServiceProperty, value); }
}
public static readonly DependencyProperty FolderBrowserDialogServiceProperty =
DependencyProperty.Register("FolderBrowserDialogService", typeof(IFolderBrowserDialogService), typeof(DirectoryPicker), new UIPropertyMetadata(null));
/// <summary>
/// The browse.
/// </summary>
private void Browse()
{
if (FolderBrowserDialogService != null)
{
var directory = Directory;
if (FolderBrowserDialogService.ShowFolderBrowserDialog(ref directory))
{
Directory = directory;
}
}
else
{
// use default win32 dialog
var d = new BrowseForFolderDialog();
d.InitialFolder = Directory;
if (true == d.ShowDialog())
{
Directory = d.SelectedFolder;
}
}
}
}
/// <summary>
/// The i directory dialog.
/// </summary>
public interface IFolderBrowserDialogService
{
bool ShowFolderBrowserDialog(ref string directory, bool showNewFolderButton = true, string description = null, bool useDescriptionForTitle = true);
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Controls/FilePicker/DirectoryPicker.cs | C# | gpl3 | 3,807 |
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.Win32;
namespace PropertyTools.Wpf
{
/// <summary>
/// FilePicker control
/// </summary>
public class FilePicker : Control
{
public static readonly DependencyProperty FilePathProperty =
DependencyProperty.Register("FilePath", typeof(string), typeof(FilePicker),
new FrameworkPropertyMetadata(null,
FrameworkPropertyMetadataOptions.
BindsTwoWayByDefault));
public static readonly DependencyProperty FilterProperty =
DependencyProperty.Register("Filter", typeof(string), typeof(FilePicker), new UIPropertyMetadata(null));
public static readonly DependencyProperty DefaultExtensionProperty =
DependencyProperty.Register("DefaultExtension", typeof(string), typeof(FilePicker),
new UIPropertyMetadata(null));
static FilePicker()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(FilePicker),
new FrameworkPropertyMetadata(typeof(FilePicker)));
}
public FilePicker()
{
BrowseCommand = new DelegateCommand(Browse);
}
public string FilePath
{
get { return (string)GetValue(FilePathProperty); }
set { SetValue(FilePathProperty, value); }
}
public string Filter
{
get { return (string)GetValue(FilterProperty); }
set { SetValue(FilterProperty, value); }
}
public string DefaultExtension
{
get { return (string)GetValue(DefaultExtensionProperty); }
set { SetValue(DefaultExtensionProperty, value); }
}
public IFileDialogService FileDialogService
{
get { return (IFileDialogService)GetValue(FileDialogServiceProperty); }
set { SetValue(FileDialogServiceProperty, value); }
}
public bool UseOpenDialog
{
get { return (bool)GetValue(UseOpenDialogProperty); }
set { SetValue(UseOpenDialogProperty, value); }
}
public static readonly DependencyProperty UseOpenDialogProperty =
DependencyProperty.Register("UseOpenDialog", typeof(bool), typeof(FilePicker), new UIPropertyMetadata(true));
public static readonly DependencyProperty FileDialogServiceProperty =
DependencyProperty.Register("FileDialogService", typeof(IFileDialogService), typeof(FilePicker), new UIPropertyMetadata(null));
public ICommand BrowseCommand { get; set; }
private void Browse()
{
if (FileDialogService != null)
{
var filename = FilePath;
if (UseOpenDialog)
{
if (FileDialogService.ShowOpenFileDialog(ref filename, Filter, DefaultExtension))
FilePath = filename;
} else
{
if (FileDialogService.ShowSaveFileDialog(ref filename, Filter, DefaultExtension))
FilePath = filename;
}
}
else
{
// use Microsoft.Win32 dialogs
if (UseOpenDialog)
{
var d = new OpenFileDialog();
d.FileName = FilePath;
d.Filter = Filter;
d.DefaultExt = DefaultExtension;
if (true == d.ShowDialog())
{
FilePath = d.FileName;
}
}
else
{
var d = new SaveFileDialog();
d.FileName = FilePath;
d.Filter = Filter;
d.DefaultExt = DefaultExtension;
if (true == d.ShowDialog())
{
FilePath = d.FileName;
}
}
}
}
}
public interface IFileDialogService
{
bool ShowOpenFileDialog(ref string filename, string filter, string defaultExtension);
bool ShowSaveFileDialog(ref string filename, string filter, string defaultExtension);
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Controls/FilePicker/FilePicker.cs | C# | gpl3 | 4,671 |
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
namespace PropertyTools.Wpf
{
// http://bea.stollnitz.com/blog/?p=28
// http://code.msdn.microsoft.com/wpfradiobuttonlist
public class RadioButtonList : Control
{
private const string PartPanel = "PART_Panel";
private StackPanel panel;
public RadioButtonList()
{
DataContextChanged += RadioButtonList_DataContextChanged;
}
void RadioButtonList_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
UpdateContent();
}
public override void OnApplyTemplate()
{
if (panel == null)
{
panel = Template.FindName(PartPanel, this) as StackPanel;
}
UpdateContent();
}
private void UpdateContent()
{
if (panel == null)
return;
panel.Children.Clear();
if (Value == null)
return;
var enumValues = Enum.GetValues(Value.GetType()).FilterOnBrowsableAttribute();
var converter = new EnumToBooleanConverter { EnumType = Value.GetType() };
var relativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(RadioButtonList), 1);
var descriptionConverter = new EnumDescriptionConverter();
foreach (var itemValue in enumValues )
{
var rb = new RadioButton { Content = descriptionConverter.Convert(itemValue, typeof(string), null, CultureInfo.CurrentCulture) };
// rb.IsChecked = Value.Equals(itemValue);
var isCheckedBinding = new Binding("Value")
{
Converter = converter,
ConverterParameter = itemValue,
Mode = BindingMode.TwoWay,
RelativeSource = relativeSource
};
rb.SetBinding(ToggleButton.IsCheckedProperty, isCheckedBinding);
var itemMarginBinding = new Binding("ItemMargin") { RelativeSource = relativeSource };
rb.SetBinding(MarginProperty, itemMarginBinding);
panel.Children.Add(rb);
}
}
static RadioButtonList()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(RadioButtonList),
new FrameworkPropertyMetadata(typeof(RadioButtonList)));
}
public Thickness ItemMargin
{
get { return (Thickness)GetValue(ItemMarginProperty); }
set { SetValue(ItemMarginProperty, value); }
}
public static readonly DependencyProperty ItemMarginProperty =
DependencyProperty.Register("ItemMargin", typeof(Thickness), typeof(RadioButtonList), new UIPropertyMetadata(new Thickness(0, 4, 0, 4)));
public Enum Value
{
get { return (Enum)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(Enum), typeof(RadioButtonList),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, ValueChanged));
private static void ValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((RadioButtonList)d).UpdateContent();
}
}
//public class EnumRadioButton : RadioButton
//{
// public Enum EnumValue
// {
// get { return (Enum)GetValue(EnumValueProperty); }
// set { SetValue(EnumValueProperty, value); }
// }
// public static readonly DependencyProperty EnumValueProperty =
// DependencyProperty.Register("EnumValue", typeof(object), typeof(EnumRadioButton), new UIPropertyMetadata(null, EnumChanged));
// private static void EnumChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
// {
// ((EnumRadioButton)d).OnEnumChanged();
// }
// private void OnEnumChanged()
// {
// IsChecked = EnumValue == Value;
// }
// public Enum Value
// {
// get { return (Enum)GetValue(ValueProperty); }
// set { SetValue(ValueProperty, value); }
// }
// public static readonly DependencyProperty ValueProperty =
// DependencyProperty.Register("Value", typeof(Enum), typeof(EnumRadioButton), new UIPropertyMetadata(null, EnumChanged));
//}
}
| zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Controls/RadioButtonList/RadioButtonList.cs | C# | gpl3 | 5,041 |
using System;
using System.Windows;
using System.Windows.Controls;
namespace PropertyTools.Wpf
{
public class EnumMenuItem : MenuItem
{
public static readonly DependencyProperty SelectedValueProperty =
DependencyProperty.Register("SelectedValue", typeof(Enum), typeof(EnumMenuItem), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, SelectedValueChanged));
public Enum SelectedValue
{
get { return (Enum)GetValue(SelectedValueProperty); }
set { SetValue(SelectedValueProperty, value); }
}
private static void SelectedValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((EnumMenuItem)d).OnSelectedValueChanged();
}
private void OnSelectedValueChanged()
{
Items.Clear();
if (SelectedValue == null)
{
return;
}
var enumType = SelectedValue.GetType();
foreach (var value in Enum.GetValues(enumType))
{
var mi = new MenuItem { Header = value.ToString(), Tag = value };
if (value.Equals(SelectedValue))
{
mi.IsChecked = true;
}
mi.Click += ItemClick;
Items.Add(mi);
}
}
private void ItemClick(object sender, RoutedEventArgs e)
{
var newValue = ((MenuItem)sender).Tag as Enum;
if (newValue != null && !newValue.Equals(SelectedValue))
{
SelectedValue = newValue;
}
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Controls/EnumMenuItem.cs | C# | gpl3 | 1,744 |
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace PropertyTools.Wpf
{
/// <summary>
/// Code Project article
/// http://www.codeproject.com/KB/WPF/DockPanelSplitter.aspx
///
/// CodePlex project
/// http://wpfcontrols.codeplex.com
///
/// DockPanelSplitter is a splitter control for DockPanels.
/// Add the DockPanelSplitter after the element you want to resize.
/// Set the DockPanel.Dock to define which edge the splitter should work on.
///
/// Follow steps 1a or 1b and then 2 to use this custom control in a XAML file.
///
/// Step 1a) Using this custom control in a XAML file that exists in the current project.
/// Add this XmlNamespace attribute to the root element of the markup file where it is
/// to be used:
///
/// xmlns:OsDps="clr-namespace:DockPanelSplitter"
///
///
/// Step 1b) Using this custom control in a XAML file that exists in a different project.
/// Add this XmlNamespace attribute to the root element of the markup file where it is
/// to be used:
///
/// xmlns:MyNamespace="clr-namespace:DockPanelSplitter;assembly=DockPanelSplitter"
///
/// You will also need to add a project reference from the project where the XAML file lives
/// to this project and Rebuild to avoid compilation errors:
///
/// Right click on the target project in the Solution Explorer and
/// "Add Reference"->"Projects"->[Select this project]
///
///
/// Step 2)
/// Go ahead and use your control in the XAML file.
///
/// <MyNamespace:DockPanelSplitter/>
///
/// </summary>
public class DockPanelSplitter : Control
{
static DockPanelSplitter()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(DockPanelSplitter), new FrameworkPropertyMetadata(typeof(DockPanelSplitter)));
// override the Background property
BackgroundProperty.OverrideMetadata(typeof(DockPanelSplitter), new FrameworkPropertyMetadata(Brushes.Transparent));
// override the Dock property to get notifications when Dock is changed
DockPanel.DockProperty.OverrideMetadata(typeof(DockPanelSplitter),
new FrameworkPropertyMetadata(Dock.Left, new PropertyChangedCallback(DockChanged)));
}
/// <summary>
/// Resize the target element proportionally with the parent container
/// Set to false if you don't want the element to be resized when the parent is resized.
/// </summary>
public bool ProportionalResize
{
get { return (bool)GetValue(ProportionalResizeProperty); }
set { SetValue(ProportionalResizeProperty, value); }
}
public static readonly DependencyProperty ProportionalResizeProperty =
DependencyProperty.Register("ProportionalResize", typeof(bool), typeof(DockPanelSplitter),
new UIPropertyMetadata(true));
/// <summary>
/// Height or width of splitter, depends of orientation of the splitter
/// </summary>
public double Thickness
{
get { return (double)GetValue(ThicknessProperty); }
set { SetValue(ThicknessProperty, value); }
}
public static readonly DependencyProperty ThicknessProperty =
DependencyProperty.Register("Thickness", typeof(double), typeof(DockPanelSplitter),
new UIPropertyMetadata(4.0, ThicknessChanged));
#region Private fields
private FrameworkElement element; // element to resize (target element)
private double width; // current desired width of the element, can be less than minwidth
private double height; // current desired height of the element, can be less than minheight
private double previousParentWidth; // current width of parent element, used for proportional resize
private double previousParentHeight; // current height of parent element, used for proportional resize
#endregion
public DockPanelSplitter()
{
Loaded += DockPanelSplitterLoaded;
Unloaded += DockPanelSplitterUnloaded;
UpdateHeightOrWidth();
}
void DockPanelSplitterLoaded(object sender, RoutedEventArgs e)
{
Panel dp = Parent as Panel;
if (dp == null) return;
// Subscribe to the parent's size changed event
dp.SizeChanged += ParentSizeChanged;
// Store the current size of the parent DockPanel
previousParentWidth = dp.ActualWidth;
previousParentHeight = dp.ActualHeight;
// Find the target element
UpdateTargetElement();
}
void DockPanelSplitterUnloaded(object sender, RoutedEventArgs e)
{
Panel dp = Parent as Panel;
if (dp == null) return;
// Unsubscribe
dp.SizeChanged -= ParentSizeChanged;
}
private static void DockChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((DockPanelSplitter)d).UpdateHeightOrWidth();
}
private static void ThicknessChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((DockPanelSplitter)d).UpdateHeightOrWidth();
}
private void UpdateHeightOrWidth()
{
if (IsHorizontal)
{
Height = Thickness;
Width = double.NaN;
}
else
{
Width = Thickness;
Height = double.NaN;
}
}
public bool IsHorizontal
{
get
{
Dock dock = DockPanel.GetDock(this);
return dock == Dock.Top || dock == Dock.Bottom;
}
}
/// <summary>
/// Update the target element (the element the DockPanelSplitter works on)
/// </summary>
private void UpdateTargetElement()
{
Panel dp = Parent as Panel;
if (dp == null) return;
int i = dp.Children.IndexOf(this);
// The splitter cannot be the first child of the parent DockPanel
// The splitter works on the 'older' sibling
if (i > 0 && dp.Children.Count > 0)
{
element = dp.Children[i - 1] as FrameworkElement;
}
}
private void SetTargetWidth(double newWidth)
{
if (newWidth < element.MinWidth)
newWidth = element.MinWidth;
if (newWidth > element.MaxWidth)
newWidth = element.MaxWidth;
// todo - constrain the width of the element to the available client area
Panel dp = Parent as Panel;
Dock dock = DockPanel.GetDock(this);
MatrixTransform t = element.TransformToAncestor(dp) as MatrixTransform;
if (dock == Dock.Left && newWidth > dp.ActualWidth - t.Matrix.OffsetX - Thickness)
newWidth = dp.ActualWidth - t.Matrix.OffsetX - Thickness;
element.Width = newWidth;
}
private void SetTargetHeight(double newHeight)
{
if (newHeight < element.MinHeight)
newHeight = element.MinHeight;
if (newHeight > element.MaxHeight)
newHeight = element.MaxHeight;
// todo - constrain the height of the element to the available client area
Panel dp = Parent as Panel;
Dock dock = DockPanel.GetDock(this);
MatrixTransform t = element.TransformToAncestor(dp) as MatrixTransform;
if (dock == Dock.Top && newHeight > dp.ActualHeight - t.Matrix.OffsetY - Thickness)
newHeight = dp.ActualHeight - t.Matrix.OffsetY - Thickness;
element.Height = newHeight;
}
private void ParentSizeChanged(object sender, SizeChangedEventArgs e)
{
if (!ProportionalResize) return;
DockPanel dp = Parent as DockPanel;
if (dp == null) return;
double sx = dp.ActualWidth / previousParentWidth;
double sy = dp.ActualHeight / previousParentHeight;
if (!double.IsInfinity(sx))
SetTargetWidth(element.Width * sx);
if (!double.IsInfinity(sy))
SetTargetHeight(element.Height * sy);
previousParentWidth = dp.ActualWidth;
previousParentHeight = dp.ActualHeight;
}
double AdjustWidth(double dx, Dock dock)
{
if (dock == Dock.Right)
dx = -dx;
width += dx;
SetTargetWidth(width);
return dx;
}
double AdjustHeight(double dy, Dock dock)
{
if (dock == Dock.Bottom)
dy = -dy;
height += dy;
SetTargetHeight(height);
return dy;
}
Point StartDragPoint;
protected override void OnMouseEnter(MouseEventArgs e)
{
base.OnMouseEnter(e);
if (!IsEnabled) return;
Cursor = IsHorizontal ? Cursors.SizeNS : Cursors.SizeWE;
}
protected override void OnMouseDown(MouseButtonEventArgs e)
{
if (!IsEnabled) return;
if (!IsMouseCaptured)
{
StartDragPoint = e.GetPosition(Parent as IInputElement);
UpdateTargetElement();
if (element != null)
{
width = element.ActualWidth;
height = element.ActualHeight;
CaptureMouse();
}
}
base.OnMouseDown(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (IsMouseCaptured)
{
Point ptCurrent = e.GetPosition(Parent as IInputElement);
Point delta = new Point(ptCurrent.X - StartDragPoint.X, ptCurrent.Y - StartDragPoint.Y);
Dock dock = DockPanel.GetDock(this);
if (IsHorizontal)
delta.Y = AdjustHeight(delta.Y, dock);
else
delta.X = AdjustWidth(delta.X, dock);
bool isBottomOrRight = (dock == Dock.Right || dock == Dock.Bottom);
// When docked to the bottom or right, the position has changed after adjusting the size
if (isBottomOrRight)
StartDragPoint = e.GetPosition(Parent as IInputElement);
else
StartDragPoint = new Point(StartDragPoint.X + delta.X, StartDragPoint.Y + delta.Y);
}
base.OnMouseMove(e);
}
protected override void OnMouseUp(MouseButtonEventArgs e)
{
if (IsMouseCaptured)
{
ReleaseMouseCapture();
}
base.OnMouseUp(e);
}
}
}
| zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Controls/DockPanelSplitter/DockPanelSplitter.cs | C# | gpl3 | 11,533 |
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace PropertyTools.Wpf
{
/// <summary>
/// The Bitmap element is using the ActualWidth/Height of the image for the control size.
/// It also offsets the image to avoid blurring over pixel boundaries. (todo: Can this also be achieved with SnapToDevicePixels?)
/// http://blogs.msdn.com/b/dwayneneed/archive/2007/10/05/blurry-bitmaps.aspx
/// </summary>
public class Bitmap : UIElement
{
public static readonly DependencyProperty SourceProperty = DependencyProperty.Register(
"Source",
typeof (BitmapSource),
typeof (Bitmap),
new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.AffectsRender |
FrameworkPropertyMetadataOptions.AffectsMeasure,
OnSourceChanged));
private readonly EventHandler _sourceDownloaded;
private readonly EventHandler<ExceptionEventArgs> _sourceFailed;
private Point _pixelOffset;
public Bitmap()
{
_sourceDownloaded = new EventHandler(OnSourceDownloaded);
_sourceFailed = new EventHandler<ExceptionEventArgs>(OnSourceFailed);
LayoutUpdated += OnLayoutUpdated;
}
public BitmapSource Source
{
get { return (BitmapSource) GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
public event EventHandler<ExceptionEventArgs> BitmapFailed;
// Return our measure size to be the size needed to display the bitmap pixels.
protected override Size MeasureCore(Size availableSize)
{
var measureSize = new Size();
BitmapSource bitmapSource = Source;
if (bitmapSource != null)
{
PresentationSource ps = PresentationSource.FromVisual(this);
if (ps != null)
{
Matrix fromDevice = ps.CompositionTarget.TransformFromDevice;
var pixelSize = new Vector(bitmapSource.PixelWidth, bitmapSource.PixelHeight);
Vector measureSizeV = fromDevice.Transform(pixelSize);
measureSize = new Size(measureSizeV.X, measureSizeV.Y);
}
}
return measureSize;
}
protected override void OnRender(DrawingContext dc)
{
BitmapSource bitmapSource = Source;
if (bitmapSource != null)
{
_pixelOffset = GetPixelOffset();
// Render the bitmap offset by the needed amount to align to pixels.
dc.DrawImage(bitmapSource, new Rect(_pixelOffset, DesiredSize));
}
}
private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var bitmap = (Bitmap) d;
var oldValue = (BitmapSource) e.OldValue;
var newValue = (BitmapSource) e.NewValue;
if (((oldValue != null) && (bitmap._sourceDownloaded != null)) &&
(!oldValue.IsFrozen && (oldValue is BitmapSource)))
{
(oldValue).DownloadCompleted -= bitmap._sourceDownloaded;
(oldValue).DownloadFailed -= bitmap._sourceFailed;
// ((BitmapSource)newValue).DecodeFailed -= bitmap._sourceFailed; // 3.5
}
if (((newValue != null) && (newValue is BitmapSource)) && !newValue.IsFrozen)
{
(newValue).DownloadCompleted += bitmap._sourceDownloaded;
(newValue).DownloadFailed += bitmap._sourceFailed;
// ((BitmapSource)newValue).DecodeFailed += bitmap._sourceFailed; // 3.5
}
}
private void OnSourceDownloaded(object sender, EventArgs e)
{
InvalidateMeasure();
InvalidateVisual();
}
private void OnSourceFailed(object sender, ExceptionEventArgs e)
{
Source = null; // setting a local value seems scetchy...
BitmapFailed(this, e);
}
private void OnLayoutUpdated(object sender, EventArgs e)
{
// This event just means that layout happened somewhere. However, this is
// what we need since layout anywhere could affect our pixel positioning.
Point pixelOffset = GetPixelOffset();
if (!AreClose(pixelOffset, _pixelOffset))
{
InvalidateVisual();
}
}
// Gets the matrix that will convert a point from "above" the
// coordinate space of a visual into the the coordinate space
// "below" the visual.
private Matrix GetVisualTransform(Visual v)
{
if (v != null)
{
Matrix m = Matrix.Identity;
Transform transform = VisualTreeHelper.GetTransform(v);
if (transform != null)
{
Matrix cm = transform.Value;
m = Matrix.Multiply(m, cm);
}
Vector offset = VisualTreeHelper.GetOffset(v);
m.Translate(offset.X, offset.Y);
return m;
}
return Matrix.Identity;
}
private Point TryApplyVisualTransform(Point point, Visual v, bool inverse, bool throwOnError, out bool success)
{
success = true;
if (v != null)
{
Matrix visualTransform = GetVisualTransform(v);
if (inverse)
{
if (!throwOnError && !visualTransform.HasInverse)
{
success = false;
return new Point(0, 0);
}
visualTransform.Invert();
}
point = visualTransform.Transform(point);
}
return point;
}
private Point ApplyVisualTransform(Point point, Visual v, bool inverse)
{
bool success = true;
return TryApplyVisualTransform(point, v, inverse, true, out success);
}
private Point GetPixelOffset()
{
var pixelOffset = new Point();
PresentationSource ps = PresentationSource.FromVisual(this);
if (ps != null)
{
Visual rootVisual = ps.RootVisual;
// Transform (0,0) from this element up to pixels.
pixelOffset = TransformToAncestor(rootVisual).Transform(pixelOffset);
pixelOffset = ApplyVisualTransform(pixelOffset, rootVisual, false);
pixelOffset = ps.CompositionTarget.TransformToDevice.Transform(pixelOffset);
// Round the origin to the nearest whole pixel.
pixelOffset.X = Math.Round(pixelOffset.X);
pixelOffset.Y = Math.Round(pixelOffset.Y);
// Transform the whole-pixel back to this element.
pixelOffset = ps.CompositionTarget.TransformFromDevice.Transform(pixelOffset);
pixelOffset = ApplyVisualTransform(pixelOffset, rootVisual, true);
pixelOffset = rootVisual.TransformToDescendant(this).Transform(pixelOffset);
}
return pixelOffset;
}
private bool AreClose(Point point1, Point point2)
{
return AreClose(point1.X, point2.X) && AreClose(point1.Y, point2.Y);
}
private bool AreClose(double value1, double value2)
{
if (value1 == value2)
{
return true;
}
double delta = value1 - value2;
return ((delta < 1.53E-06) && (delta > -1.53E-06));
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Controls/Bitmap.cs | C# | gpl3 | 8,143 |
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace PropertyTools.Wpf
{
/// <summary>
/// Captures screenshot using WINAPI.
/// http://stackoverflow.com/questions/1736287/capturing-a-window-with-wpf
/// </summary>
static public class CaptureScreenshot
{
/// <summary>
/// Capture the screenshot.
/// <param name="area">Area of screenshot.</param>
/// <returns>Bitmap source that can be used e.g. as background.</returns>
/// </summary>
public static BitmapSource Capture(Rect area)
{
IntPtr screenDC = GetDC(IntPtr.Zero);
IntPtr memDC = CreateCompatibleDC(screenDC);
IntPtr hBitmap = CreateCompatibleBitmap(screenDC, (int)area.Width, (int)area.Height);
SelectObject(memDC, hBitmap); // Select bitmap from compatible bitmap to memDC
// TODO: BitBlt may fail horribly
BitBlt(memDC, 0, 0, (int)area.Width, (int)area.Height, screenDC, (int)area.X, (int)area.Y, TernaryRasterOperations.SRCCOPY);
BitmapSource bsource = Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
DeleteObject(hBitmap);
ReleaseDC(IntPtr.Zero, screenDC);
ReleaseDC(IntPtr.Zero, memDC);
return bsource;
}
#region WINAPI DLL Imports
[DllImport("gdi32.dll", ExactSpelling = true, PreserveSig = true, SetLastError = true)]
static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj);
[DllImport("gdi32.dll")]
private static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight);
[DllImport("gdi32.dll", SetLastError = true)]
private static extern IntPtr CreateCompatibleDC(IntPtr hdc);
[DllImport("gdi32.dll")]
private static extern bool DeleteObject(IntPtr hObject);
[DllImport("gdi32.dll")]
private static extern IntPtr CreateBitmap(int nWidth, int nHeight, uint cPlanes, uint cBitsPerPel, IntPtr lpvBits);
[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
private enum TernaryRasterOperations : uint
{
/// <summary>dest = source</summary>
SRCCOPY = 0x00CC0020,
/// <summary>dest = source OR dest</summary>
SRCPAINT = 0x00EE0086,
/// <summary>dest = source AND dest</summary>
SRCAND = 0x008800C6,
/// <summary>dest = source XOR dest</summary>
SRCINVERT = 0x00660046,
/// <summary>dest = source AND (NOT dest)</summary>
SRCERASE = 0x00440328,
/// <summary>dest = (NOT source)</summary>
NOTSRCCOPY = 0x00330008,
/// <summary>dest = (NOT src) AND (NOT dest)</summary>
NOTSRCERASE = 0x001100A6,
/// <summary>dest = (source AND pattern)</summary>
MERGECOPY = 0x00C000CA,
/// <summary>dest = (NOT source) OR dest</summary>
MERGEPAINT = 0x00BB0226,
/// <summary>dest = pattern</summary>
PATCOPY = 0x00F00021,
/// <summary>dest = DPSnoo</summary>
PATPAINT = 0x00FB0A09,
/// <summary>dest = pattern XOR dest</summary>
PATINVERT = 0x005A0049,
/// <summary>dest = (NOT dest)</summary>
DSTINVERT = 0x00550009,
/// <summary>dest = BLACK</summary>
BLACKNESS = 0x00000042,
/// <summary>dest = WHITE</summary>
WHITENESS = 0x00FF0062
}
[DllImport("gdi32.dll")]
private static extern bool BitBlt(IntPtr hdc, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, TernaryRasterOperations dwRop);
#endregion
public static Point GetMouseScreenPosition()
{
Win32Point w32Mouse = new Win32Point();
GetCursorPos(ref w32Mouse);
return new Point(w32Mouse.X, w32Mouse.Y);
}
// http://www.switchonthecode.com/tutorials/wpf-snippet-reliably-getting-the-mouse-position
public static Point CorrectGetPosition(Visual relativeTo)
{
Win32Point w32Mouse = new Win32Point();
GetCursorPos(ref w32Mouse);
return relativeTo.PointFromScreen(new Point(w32Mouse.X, w32Mouse.Y));
}
[StructLayout(LayoutKind.Sequential)]
internal struct Win32Point
{
public Int32 X;
public Int32 Y;
};
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetCursorPos(ref Win32Point pt);
}
}
| zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Controls/ColorPicker/CaptureScreenshot.cs | C# | gpl3 | 5,103 |
// Persistent color palette support courtesy of Per Malmberg <per.malmberg@gmail.com>
//
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Controls;
using System.Windows.Shapes;
using PropertyTools.Wpf.Controls.ColorPicker;
namespace PropertyTools.Wpf
{
/// <summary>
///
/// </summary>
public partial class ColorPicker
{
private enum Mode { None, Add, Remove, Update };
/// <summary>
/// Gets or sets the settings file where the ColorPicker will store user settings.
/// </summary>
/// <value>The settings file.</value>
public static string SettingsFile { get; set; }
public static string DefaultPalettePath { get; set; }
// Private as it should never be used outside the ColorPicker class
private static readonly DependencyProperty SelectedPersistentColorProperty =
DependencyProperty.Register( "SelectedPersistentColor", typeof( ColorWrapper ), typeof( ColorPicker ),
new FrameworkPropertyMetadata( new ColorWrapper( Colors.Black ),
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
SelectedPersistentColorChanged ) );
public static readonly DependencyProperty PersistentPaletteProperty =
DependencyProperty.Register( "PersistentPalette", typeof( ObservableCollection<ColorWrapper> ), typeof( ColorPicker ),
new UIPropertyMetadata( CreateEmptyPalette() ) );
public static readonly DependencyProperty CurrentStoreProperty =
DependencyProperty.Register( "CurrentStore", typeof( string ), typeof( ColorPicker ),
new FrameworkPropertyMetadata( "",
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault ) );
/// <summary>
/// Reference to the listbox that holds the static palette
/// </summary>
private ListBox staticList;
/// <summary>
/// Reference to the listbox that holds the persistent palette
/// </summary>
private ListBox persistentList;
/// <summary>
/// Event handler for use by multiple controls
/// </summary>
private MouseButtonEventHandler mouseEvent;
public ObservableCollection<ColorWrapper> PersistentPalette
{
get { return (ObservableCollection<ColorWrapper>)GetValue( PersistentPaletteProperty ); }
set { SetValue( PersistentPaletteProperty, value ); }
}
public ColorWrapper SelectedPersistentColor
{
get { return (ColorWrapper)GetValue( SelectedPersistentColorProperty ); }
set { SetValue( SelectedPersistentColorProperty, value ); }
}
public string CurrentStore
{
get { return (string)GetValue( CurrentStoreProperty ); }
set { SetValue( CurrentStoreProperty, value ); }
}
/// <summary>
/// Links the palette event handlers.
/// </summary>
private void InitializePaletteSettings()
{
SettingsFile = System.IO.Path.Combine( Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData ), "colorpicker.settings" );
DefaultPalettePath = System.IO.Path.Combine( Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData ), "colorpicker.default.palette" );
// Find and setup the event handler for the palettes in the ControlTemplate
persistentList = Template.FindName( "PART_PersistentColorList", this ) as ListBox;
if( persistentList != null ) {
persistentList.MouseUp += mouseEvent;
}
staticList = Template.FindName( "PART_StaticColorList", this ) as ListBox;
if( staticList != null ) {
staticList.MouseUp += mouseEvent;
}
// Allow user to click on the color box to add the current color to the palette
Rectangle rect = Template.FindName( "PART_CurrentColorBox", this ) as Rectangle;
if( rect != null ) {
rect.MouseUp += mouseEvent;
}
Button b = Template.FindName( "PART_LoadPalette", this ) as Button;
if( b != null ) {
b.Click += new RoutedEventHandler( LoadPalette_Click );
}
b = Template.FindName( "PART_SavePalette", this ) as Button;
if( b != null ) {
b.Click += new RoutedEventHandler( SavePalette_Click );
}
}
/// <summary>
/// Handles the Click event of the LoadPalette control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
void LoadPalette_Click( object sender, RoutedEventArgs e )
{
try {
using( System.Windows.Forms.OpenFileDialog open = new System.Windows.Forms.OpenFileDialog() ) {
open.InitialDirectory = Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData );
open.Filter = "Palette files (*.palette)|*.palette";
open.FilterIndex = 0;
open.RestoreDirectory = true;
open.CheckFileExists = true;
open.CheckPathExists = true;
open.DefaultExt = "palette";
open.Multiselect = false;
if( open.ShowDialog() == System.Windows.Forms.DialogResult.OK ) {
LoadPalette( this, open.FileName );
}
}
}
catch( Exception ex ) {
MessageBox.Show( ex.Message, "Error" );
}
}
/// <summary>
/// Handles the Click event of the SavePalette control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
void SavePalette_Click( object sender, RoutedEventArgs e )
{
try {
using( System.Windows.Forms.SaveFileDialog save = new System.Windows.Forms.SaveFileDialog() ) {
save.InitialDirectory = Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData );
save.Filter = "Palette files (*.palette)|*.palette";
save.FilterIndex = 0;
save.RestoreDirectory = true;
save.OverwritePrompt = true;
save.CheckPathExists = true;
save.DefaultExt = "palette";
save.AddExtension = true;
if( save.ShowDialog() == System.Windows.Forms.DialogResult.OK ) {
StorePalette( this, save.FileName );
}
}
}
catch( Exception ex ) {
MessageBox.Show( ex.Message, "Error" );
}
}
/// <summary>
/// Handles the MouseUp event of the PersistentList control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.Input.MouseButtonEventArgs"/> instance containing the event data.</param>
void PaletteList_MouseUp( object sender, MouseButtonEventArgs e )
{
ColorWrapper cw = persistentList.SelectedItem as ColorWrapper;
ObservableCollection<ColorWrapper> items = persistentList.ItemsSource as ObservableCollection<ColorWrapper>;
if( items != null ) {
// Get the operation mode based on either keys or mouse click-position
Mode m = GetMode( sender, e );
if( m == Mode.Add ) {
// Add another color item
items.Insert( 0, new ColorWrapper( SelectedColor ) );
UpdateCurrentPaletteStore();
}
else if( m == Mode.Remove ) {
// Remove current color, but only if there are two or more items left and there is a selected item
// and the user clicked the persistent list
if( cw != null && items.Count > 1 ) {
items.Remove( cw );
UpdateCurrentPaletteStore();
}
}
else if( cw != null ) {
if( m == Mode.Update ) {
// Update the persistent palette with the current color
cw.Color = SelectedColor;
UpdateCurrentPaletteStore();
}
else if( sender == persistentList ) {
// No key pressed, just update the current color
SelectedColor = cw.Color;
}
}
// Event handled if mode was anything other than None
e.Handled = m != Mode.None;
}
}
/// <summary>
/// Gets the mode of operation
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.Windows.Input.MouseButtonEventArgs"/> instance containing the event data.</param>
/// <returns>The mode of operation for the click event</returns>
private Mode GetMode( object sender, MouseButtonEventArgs e )
{
Mode result = Mode.None;
if( e.ChangedButton == MouseButton.Right ) {
// User used the right button to click, get mode based on where he/she clicked.
if( sender == persistentList ) {
// Only update or remove modes possible when clicking the persistent list
if( Keyboard.IsKeyDown( Key.LeftShift ) || Keyboard.IsKeyDown( Key.RightShift ) ) {
result = Mode.Remove;
}
else if( Keyboard.IsKeyDown( Key.LeftCtrl ) || Keyboard.IsKeyDown( Key.RightCtrl ) ) {
result = Mode.Update;
}
}
else {
// All other clicks results in an added color.
result = Mode.Add;
}
}
return result;
}
/// <summary>
/// Updates the current palette store.
/// </summary>
private void UpdateCurrentPaletteStore()
{
try {
if( File.Exists( SettingsFile ) ) {
string s = File.ReadAllText( SettingsFile, Encoding.UTF8 );
StorePalette( this, s );
}
}
catch( Exception ) {
// Silently ignore
}
}
/// <summary>
/// Creates the empty palette.
/// </summary>
/// <returns></returns>
public static ObservableCollection<ColorWrapper> CreateEmptyPalette()
{
// Create an 'empty' palette with a few transparent items.
ObservableCollection<ColorWrapper> palette = new ObservableCollection<ColorWrapper>();
for( int i = 0; i < 8; ++i ) {
palette.Add( new ColorWrapper( Colors.Transparent ) );
}
return palette;
}
/// <summary>
/// Stores the palette.
/// </summary>
/// <param name="picker">The picker.</param>
/// <param name="path">The path.</param>
public void StorePalette( ColorPicker picker, string path )
{
// Write the colors as text
StringBuilder sb = new StringBuilder();
foreach( ColorWrapper cw in picker.PersistentPalette ) {
sb.AppendFormat( "{0}\n", cw.Color.ToString( CultureInfo.InvariantCulture ) );
}
File.WriteAllText( path, sb.ToString(), Encoding.UTF8 );
StoreLastUsedPalette( path );
}
/// <summary>
/// Stores the last used palette.
/// </summary>
/// <param name="path">The path.</param>
private void StoreLastUsedPalette( string path )
{
// Store last used palette
try {
File.WriteAllText( SettingsFile, path, Encoding.UTF8 );
CurrentStore = System.IO.Path.GetFileNameWithoutExtension( path );
}
catch( Exception ) { }
}
/// <summary>
/// Loads the palette.
/// </summary>
/// <param name="picker">The picker.</param>
/// <param name="path">The path.</param>
public void LoadPalette( ColorPicker picker, string path )
{
string s = File.ReadAllText( path, Encoding.UTF8 );
string[] colors = s.Split( new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries );
StoreLastUsedPalette( path );
ObservableCollection<ColorWrapper> palette = new ObservableCollection<ColorWrapper>();
foreach( string c in colors ) {
try {
Color color = (Color)ColorConverter.ConvertFromString( c );
palette.Add( new ColorWrapper( color ) );
}
catch {
// Silently ignore
}
}
picker.PersistentPalette = palette.Count > 0 ? palette : CreateEmptyPalette();
}
private void LoadLastPalette()
{
try {
if( !File.Exists( SettingsFile ) ) {
// Use default palette
StorePalette( this, DefaultPalettePath );
}
LoadPalette( this, File.ReadAllText( SettingsFile, Encoding.UTF8 ) );
}
catch( Exception ) { }
}
}
}
| zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Controls/ColorPicker/ColorPickerPalette.cs | C# | gpl3 | 11,861 |
using System.ComponentModel;
using System.Windows.Media;
namespace PropertyTools.Wpf.Controls.ColorPicker
{
/// <summary>
/// Wrapper class for colors - needed to get unique items in the persistent color list
/// since Color.XXX added in multiple positions results in multiple items being selected.
/// Also needed to implement the INotifyPropertyChanged for binding support.
/// </summary>
public class ColorWrapper : INotifyPropertyChanged
{
private Color color;
public ColorWrapper(Color c)
{
Color = c;
}
public Color Color
{
get { return color; }
set
{
color = value;
OnPropertyChanged("Color");
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Controls/ColorPicker/ColorWrapper.cs | C# | gpl3 | 1,214 |
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
namespace PropertyTools.Wpf
{
/// <summary>
/// ColorPicker control
/// </summary>
public partial class ColorPicker : Control, INotifyPropertyChanged
{
// todo:
// - localize strings...
// - more palettes
// - persist palette - in static list, and static load/save methods?
// - the user can also bind the Palette and do the persisting
// - 'automatic' color? 'IncludeAutoColor' dependency property?
public static readonly DependencyProperty ShowAsHexProperty =
DependencyProperty.Register("ShowAsHex", typeof(bool), typeof(ColorPicker), new UIPropertyMetadata(false));
public static readonly DependencyProperty PaletteProperty =
DependencyProperty.Register("Palette", typeof(ObservableCollection<Color>), typeof(ColorPicker),
new UIPropertyMetadata(CreateDefaultPalette()));
public static readonly DependencyProperty IsDropDownOpenProperty =
DependencyProperty.Register("IsDropDownOpen", typeof(bool), typeof(ColorPicker),
new UIPropertyMetadata(false, IsDropDownOpenChanged, CoerceIsDropDownOpen));
public static readonly DependencyProperty IsPickingProperty =
DependencyProperty.Register("IsPicking", typeof(bool), typeof(ColorPicker),
new UIPropertyMetadata(false, IsPickingChanged));
public static readonly DependencyProperty SelectedColorProperty =
DependencyProperty.Register("SelectedColor", typeof(Color), typeof(ColorPicker),
new FrameworkPropertyMetadata(Color.FromArgb(80, 255, 255, 0),
FrameworkPropertyMetadataOptions.
BindsTwoWayByDefault,
SelectedColorChanged));
public static readonly DependencyProperty TabStripPlacementProperty =
DependencyProperty.Register("TabStripPlacement", typeof(Dock), typeof(ColorPicker),
new UIPropertyMetadata(Dock.Bottom));
private byte brightness;
private byte hue;
private DispatcherTimer pickingTimer;
private byte saturation;
private bool updateHSV = true;
private bool updateHexValue = true;
static ColorPicker()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ColorPicker),
new FrameworkPropertyMetadata(typeof(ColorPicker)));
EventManager.RegisterClassHandler(typeof(ColorPicker), Mouse.MouseDownEvent, new MouseButtonEventHandler(OnMouseButtonDown), true);
EventManager.RegisterClassHandler(typeof(ColorPicker), GotFocusEvent, new RoutedEventHandler(OnGotFocus));
}
private static void OnMouseButtonDown(object sender, MouseButtonEventArgs e)
{
var picker = (ColorPicker)sender;
if (!picker.IsKeyboardFocusWithin)
{
picker.Focus();
}
e.Handled = true;
if ((Mouse.Captured == picker) && (e.OriginalSource == picker))
{
picker.CloseDropDown();
}
}
private void CloseDropDown()
{
if (this.IsDropDownOpen)
{
this.ClearValue(IsDropDownOpenProperty);
if (this.IsDropDownOpen)
{
this.IsDropDownOpen = false;
}
}
}
private void ToggleDropDown()
{
if (this.IsDropDownOpen)
{
this.CloseDropDown();
}
else
{
this.IsDropDownOpen = true;
}
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
var handled = false;
switch (e.Key)
{
case Key.F4:
this.ToggleDropDown();
handled = true;
break;
case Key.Enter:
this.CloseDropDown();
handled = true;
break;
case Key.Escape:
this.CloseDropDown();
handled = true;
break;
}
e.Handled = handled;
}
private static void OnGotFocus(object sender, RoutedEventArgs e)
{
var picker = (ColorPicker)sender;
if (!e.Handled && picker.staticColorList != null)
{
if (e.OriginalSource == picker)
{
picker.staticColorList.Focus();
e.Handled = true;
}
else if (e.OriginalSource == picker.staticColorList)
{
picker.staticColorList.Focus();
}
}
}
private ListBox staticColorList;
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
staticColorList = Template.FindName("PART_StaticColorList", this) as ListBox;
}
public ColorPicker()
{
Loaded += ColorPicker_Loaded;
mouseEvent = new MouseButtonEventHandler(PaletteList_MouseUp);
}
public Dock TabStripPlacement
{
get { return (Dock)GetValue(TabStripPlacementProperty); }
set { SetValue(TabStripPlacementProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating whether show as color names as hex strings.
/// </summary>
/// <value><c>true</c> if show as hex; otherwise, <c>false</c>.</value>
public bool ShowAsHex
{
get { return (bool)GetValue(ShowAsHexProperty); }
set { SetValue(ShowAsHexProperty, value); }
}
public ObservableCollection<Color> Palette
{
get { return (ObservableCollection<Color>)GetValue(PaletteProperty); }
set { SetValue(PaletteProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the color picker popup is open.
/// </summary>
/// <value>
/// <c>true</c> if this popup is open; otherwise, <c>false</c>.
/// </value>
public bool IsDropDownOpen
{
get { return (bool)GetValue(IsDropDownOpenProperty); }
set { SetValue(IsDropDownOpenProperty, value); }
}
/// <summary>
/// Gets or sets if picking colors from the screen is active.
/// Use the 'SHIFT' button to select colors when this mode is active.
/// </summary>
public bool IsPicking
{
get { return (bool)GetValue(IsPickingProperty); }
set { SetValue(IsPickingProperty, value); }
}
/// <summary>
/// Gets or sets the selected color.
/// </summary>
/// <value>The color of the selected.</value>
public Color SelectedColor
{
get { return (Color)GetValue(SelectedColorProperty); }
set { SetValue(SelectedColorProperty, value); }
}
public Brush AlphaGradient
{
get { return new LinearGradientBrush(Colors.Transparent, Color.FromRgb(Red, Green, Blue), 0); }
}
public Brush SaturationGradient
{
get
{
return new LinearGradientBrush(ColorHelper.HsvToColor(Hue, 0, Brightness),
ColorHelper.HsvToColor(Hue, 255, Brightness), 0);
}
}
public Brush BrightnessGradient
{
get
{
return new LinearGradientBrush(ColorHelper.HsvToColor(Hue, Saturation, 0),
ColorHelper.HsvToColor(Hue, Saturation, 255), 0);
}
}
public string ColorName
{
get
{
if (ShowAsHex)
return ColorHelper.ColorToHex(SelectedColor);
Type t = typeof(Colors);
PropertyInfo[] fields = t.GetProperties(BindingFlags.Public | BindingFlags.Static);
string nearestColor = "Custom";
double nearestDist = 30;
// find the color that is closest
foreach (PropertyInfo fi in fields)
{
var c = (Color)fi.GetValue(null, null);
if (SelectedColor == c)
return fi.Name;
double d = ColorHelper.ColorDifference(SelectedColor, c);
if (d < nearestDist)
{
nearestColor = "~ " + fi.Name; // 'kind of'
nearestDist = d;
}
}
if (SelectedColor.A < 255)
{
return String.Format("{0}, {1:0} %", nearestColor, SelectedColor.A / 2.55);
}
return nearestColor;
}
}
public byte Red
{
get { return SelectedColor.R; }
set { SelectedColor = Color.FromArgb(Alpha, value, Green, Blue); }
}
public byte Green
{
get { return SelectedColor.G; }
set { SelectedColor = Color.FromArgb(Alpha, Red, value, Blue); }
}
public byte Blue
{
get { return SelectedColor.B; }
set { SelectedColor = Color.FromArgb(Alpha, Red, Green, value); }
}
public byte Alpha
{
get { return SelectedColor.A; }
set { SelectedColor = Color.FromArgb(value, Red, Green, Blue); }
}
public byte Hue
{
get { return hue; }
set
{
updateHSV = false;
SelectedColor = ColorHelper.HsvToColor(value, Saturation, Brightness);
hue = value;
OnPropertyChanged("Hue");
}
}
public byte Saturation
{
get { return saturation; }
set
{
updateHSV = false;
SelectedColor = ColorHelper.HsvToColor(Hue, value, Brightness);
updateHSV = true;
saturation = value;
OnPropertyChanged("Saturation");
}
}
public byte Brightness
{
get { return brightness; }
set
{
updateHSV = false;
SelectedColor = ColorHelper.HsvToColor(Hue, Saturation, value);
updateHSV = true;
brightness = value;
OnPropertyChanged("Brightness");
}
}
public string HexValue
{
get
{
return ColorHelper.ColorToHex(SelectedColor);
}
set
{
updateHexValue = false;
SelectedColor = ColorHelper.HexToColor(value);
updateHexValue = true;
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
private void ColorPicker_Loaded(object sender, RoutedEventArgs e)
{
InitializePaletteSettings();
LoadLastPalette();
}
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private static void IsDropDownOpenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((ColorPicker)d).IsDropDownOpenChanged(e);
}
private static object CoerceIsDropDownOpen(DependencyObject d, object basevalue)
{
return ((ColorPicker) d).OnCoerceIsDropDownOpen(basevalue);
}
private object OnCoerceIsDropDownOpen(object basevalue)
{
if ((bool)basevalue)
{
if (!IsLoaded)
{
return false;
}
}
return basevalue;
}
private void IsDropDownOpenChanged(DependencyPropertyChangedEventArgs e)
{
Debug.WriteLine("IsDropDownOpenChanged: " + e.NewValue);
var newValue = (bool)e.NewValue;
if (newValue)
{
Mouse.Capture(this, CaptureMode.SubTree);
staticColorList.Focus();
}
else
{
if (Mouse.Captured == this)
{
Mouse.Capture(null);
}
}
// Reload last used palette each time the dropdown is opened.
if (IsDropDownOpen)
{
LoadLastPalette();
}
// turn off picking when drop down is closed
if (!IsDropDownOpen && IsPicking)
IsPicking = false;
}
private static void IsPickingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((ColorPicker)d).IsPickingChanged();
}
private void IsPickingChanged()
{
if (IsPicking && pickingTimer == null)
{
pickingTimer = new DispatcherTimer();
pickingTimer.Interval = TimeSpan.FromMilliseconds(100);
pickingTimer.Tick += Pick;
pickingTimer.Start();
}
if (!IsPicking && pickingTimer != null)
{
pickingTimer.Tick -= Pick;
pickingTimer.Stop();
pickingTimer = null;
}
}
private void Pick(object sender, EventArgs e)
{
if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
{
try
{
Point pt = CaptureScreenshot.GetMouseScreenPosition();
BitmapSource bmp = CaptureScreenshot.Capture(new Rect(pt, new Size(1, 1)));
var pixels = new byte[4];
bmp.CopyPixels(pixels, 4, 0);
SelectedColor = Color.FromArgb(0xFF, pixels[2], pixels[1], pixels[0]);
}
catch (Exception)
{
}
}
}
private static void SelectedColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((ColorPicker)d).OnSelectedValueChanged();
}
private static void SelectedPersistentColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// No action here
}
private void OnSelectedValueChanged()
{
// don't update the HSV controls if the original change was H, S or V.
if (updateHSV)
{
byte[] hsv = ColorHelper.ColorToHsvBytes(SelectedColor);
hue = hsv[0];
saturation = hsv[1];
brightness = hsv[2];
OnPropertyChanged("Hue");
OnPropertyChanged("Saturation");
OnPropertyChanged("Brightness");
}
if (updateHexValue)
{
OnPropertyChanged("HexValue");
}
OnPropertyChanged("Red");
OnPropertyChanged("Green");
OnPropertyChanged("Blue");
OnPropertyChanged("Alpha");
OnPropertyChanged("ColorName");
OnPropertyChanged("AlphaGradient");
OnPropertyChanged("SaturationGradient");
OnPropertyChanged("BrightnessGradient");
}
public static ObservableCollection<Color> CreateDefaultPalette()
{
var palette = new ObservableCollection<Color>();
// transparent colors
palette.Add(Colors.Transparent);
palette.Add(Color.FromArgb(128, 0, 0, 0));
palette.Add(Color.FromArgb(128, 255, 255, 255));
// shades of gray
palette.Add(Colors.White);
palette.Add(Colors.Silver);
palette.Add(Colors.Gray);
palette.Add(Colors.DarkSlateGray);
palette.Add(Colors.Black);
// standard colors
palette.Add(Colors.Firebrick);
palette.Add(Colors.Red);
palette.Add(Colors.Tomato);
palette.Add(Colors.OrangeRed);
palette.Add(Colors.Orange);
palette.Add(Colors.Gold);
palette.Add(Colors.Yellow);
palette.Add(Colors.YellowGreen);
palette.Add(Colors.SeaGreen);
palette.Add(Colors.DeepSkyBlue);
palette.Add(Colors.CornflowerBlue);
palette.Add(Colors.LightBlue);
palette.Add(Colors.DarkCyan);
palette.Add(Colors.MidnightBlue);
palette.Add(Colors.DarkOrchid);
// Add colors by hue
/*int N = 32 - 5;
for (int i = 0; i < N; i++)
{
double h = 0.8 * i / (N - 1);
var c = ColorHelper.HsvToColor(h, 1.0, 1.0);
palette.Add(c);
}*/
return palette;
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Controls/ColorPicker/ColorPicker.cs | C# | gpl3 | 18,682 |
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PropertyTools for WPF")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PropertyTools for WPF")]
[assembly: AssemblyCopyright("Copyright © OBJO 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2011.3.*")]
//[assembly: AssemblyFileVersion("2011.3")]
| zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Properties/AssemblyInfo.cs | C# | gpl3 | 2,247 |
using System;
using System.Windows;
namespace PropertyTools.Wpf
{
/// <summary>
/// Define formatting and templates for a given type
/// </summary>
public class TypeDefinition
{
public Type Type { get; set; }
public string StringFormat { get; set; }
public HorizontalAlignment HorizontalAlignment { get; set; }
public DataTemplate DisplayTemplate { get; set; }
public DataTemplate EditTemplate { get; set; }
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/SimpleGrid/TypeDefinition.cs | C# | gpl3 | 524 |
using System.Windows;
namespace PropertyTools.Wpf
{
public class ColumnDefinition
{
/// <summary>
/// Gets or sets the data field.
/// Note: This is not used if DisplayTemplate/EditTemplate is set.
/// </summary>
/// <value>The data field.</value>
public string DataField { get; set; }
/// <summary>
/// Gets or sets the string format.
/// </summary>
/// <value>The string format.</value>
public string StringFormat { get; set; }
/// <summary>
/// Gets or sets the header.
/// </summary>
/// <value>The header.</value>
public object Header { get; set; }
/// <summary>
/// Gets or sets the width.
/// </summary>
/// <value>The width.</value>
public GridLength Width { get; set; }
/// <summary>
/// Gets or sets the display template.
/// </summary>
/// <value>The display template.</value>
public DataTemplate DisplayTemplate { get; set; }
/// <summary>
/// Gets or sets the edit template.
/// </summary>
/// <value>The edit template.</value>
public DataTemplate EditTemplate { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance can delete.
/// </summary>
/// <value>
/// <c>true</c> if this instance can delete; otherwise, <c>false</c>.
/// </value>
public bool CanDelete { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance can resize.
/// </summary>
/// <value>
/// <c>true</c> if this instance can resize; otherwise, <c>false</c>.
/// </value>
public bool CanResize { get; set; }
/// <summary>
/// Gets or sets the horizontal alignment.
/// </summary>
/// <value>The horizontal alignment.</value>
public HorizontalAlignment HorizontalAlignment{ get; set; }
public ColumnDefinition()
{
HorizontalAlignment = HorizontalAlignment.Center;
Width = new GridLength(-1);
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/SimpleGrid/ColumnDefinition.cs | C# | gpl3 | 2,282 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace PropertyTools.Wpf
{
public partial class SimpleGrid
{
public static readonly DependencyProperty ContentProperty =
DependencyProperty.Register("Content", typeof(object), typeof(SimpleGrid),
new UIPropertyMetadata(null, ContentChanged));
public static readonly DependencyProperty CurrentCellProperty =
DependencyProperty.Register("CurrentCell", typeof(CellRef), typeof(SimpleGrid),
new FrameworkPropertyMetadata(new CellRef(0, 0),
FrameworkPropertyMetadataOptions.
BindsTwoWayByDefault, CurrentCellChanged,
CoerceCurrentCell));
public static readonly DependencyProperty SelectionCellProperty =
DependencyProperty.Register("SelectionCell", typeof(CellRef), typeof(SimpleGrid),
new UIPropertyMetadata(new CellRef(0, 0), SelectionCellChanged,
CoerceSelectionCell));
//public static readonly DependencyProperty CurrentItemProperty =
// DependencyProperty.Register("CurrentItem", typeof(object), typeof(SimpleGrid),
// new FrameworkPropertyMetadata(null,
// FrameworkPropertyMetadataOptions.
// BindsTwoWayByDefault, CurrentItemChanged));
public static readonly DependencyProperty SelectedItemsProperty =
DependencyProperty.Register("SelectedItems", typeof(IEnumerable), typeof(SimpleGrid),
new UIPropertyMetadata(null));
public static readonly DependencyProperty AllowExpandProperty =
DependencyProperty.Register("AllowExpand", typeof(bool), typeof(SimpleGrid), new UIPropertyMetadata(true));
public static readonly DependencyProperty ColumnHeadersProperty =
DependencyProperty.Register("ColumnHeaders", typeof(StringCollection), typeof(SimpleGrid),
new UIPropertyMetadata(null, ContentChanged));
public static readonly DependencyProperty FormatStringsProperty =
DependencyProperty.Register("FormatStrings", typeof(StringCollection), typeof(SimpleGrid),
new UIPropertyMetadata(null, ContentChanged));
public static readonly DependencyProperty RowHeadersProperty =
DependencyProperty.Register("RowHeaders", typeof(StringCollection), typeof(SimpleGrid),
new UIPropertyMetadata(null, ContentChanged));
public static readonly DependencyProperty DataFieldsProperty =
DependencyProperty.Register("DataFields", typeof(StringCollection), typeof(SimpleGrid),
new UIPropertyMetadata(null, ContentChanged));
public static readonly DependencyProperty ItemsInColumnsProperty =
DependencyProperty.Register("ItemsInColumns", typeof(bool), typeof(SimpleGrid),
new UIPropertyMetadata(false, ContentChanged));
public static readonly DependencyProperty RowHeaderWidthProperty =
DependencyProperty.Register("RowHeaderWidth", typeof(GridLength), typeof(SimpleGrid),
new UIPropertyMetadata(new GridLength(40)));
public static readonly DependencyProperty HeaderBorderBrushProperty =
DependencyProperty.Register("HeaderBorderBrush", typeof(Brush), typeof(SimpleGrid),
new UIPropertyMetadata(new SolidColorBrush(Color.FromRgb(177, 181, 186))));
public static readonly DependencyProperty GridLineBrushProperty =
DependencyProperty.Register("GridLineBrush", typeof(Brush), typeof(SimpleGrid),
new UIPropertyMetadata(new SolidColorBrush(Color.FromRgb(218, 220, 221))));
public static readonly DependencyProperty ColumnAlignmentsProperty =
DependencyProperty.Register("ColumnAlignments", typeof(Collection<HorizontalAlignment>),
typeof(SimpleGrid), new UIPropertyMetadata(null, ContentChanged));
public static readonly DependencyProperty ColumnWidthsProperty =
DependencyProperty.Register("ColumnWidths", typeof(Collection<GridLength>), typeof(SimpleGrid),
new UIPropertyMetadata(null, ContentChanged));
public static readonly DependencyProperty AutoSizeColumnsProperty =
DependencyProperty.Register("AutoSizeColumns", typeof(bool), typeof(SimpleGrid),
new UIPropertyMetadata(false));
public static readonly DependencyProperty CanInsertProperty =
DependencyProperty.Register("CanInsert", typeof(bool), typeof(SimpleGrid), new UIPropertyMetadata(true));
public static readonly DependencyProperty CanDeleteProperty =
DependencyProperty.Register("CanDelete", typeof(bool), typeof(SimpleGrid), new UIPropertyMetadata(true));
public static readonly DependencyProperty AlternatingRowsBackgroundProperty =
DependencyProperty.Register("AlternatingRowsBackground", typeof(Brush), typeof(SimpleGrid),
new UIPropertyMetadata(null));
public static readonly DependencyProperty DefaultColumnWidthProperty =
DependencyProperty.Register("DefaultColumnWidth", typeof(GridLength), typeof(SimpleGrid),
new UIPropertyMetadata(new GridLength(100)));
public HorizontalAlignment DefaultHorizontalAlignment
{
get { return (HorizontalAlignment)GetValue(DefaultHorizontalAlignmentProperty); }
set { SetValue(DefaultHorizontalAlignmentProperty, value); }
}
public static readonly DependencyProperty DefaultHorizontalAlignmentProperty =
DependencyProperty.Register("DefaultHorizontalAlignment", typeof(HorizontalAlignment), typeof(SimpleGrid), new UIPropertyMetadata(System.Windows.HorizontalAlignment.Center));
public static readonly DependencyProperty DefaultRowHeightProperty =
DependencyProperty.Register("DefaultRowHeight", typeof(GridLength), typeof(SimpleGrid),
new UIPropertyMetadata(new GridLength(20)));
public static readonly DependencyProperty CanResizeColumnsProperty =
DependencyProperty.Register("CanResizeColumns", typeof(bool), typeof(SimpleGrid),
new UIPropertyMetadata(true));
public static readonly DependencyProperty AddItemHeaderProperty =
DependencyProperty.Register("AddItemHeader", typeof(string), typeof(SimpleGrid),
new UIPropertyMetadata("*"));
//public object CurrentItem
//{
// get { return GetValue(CurrentItemProperty); }
// set { SetValue(CurrentItemProperty, value); }
//}
public IEnumerable SelectedItems
{
get { return (IEnumerable)GetValue(SelectedItemsProperty); }
set { SetValue(SelectedItemsProperty, value); }
}
public bool AllowExpand
{
get { return (bool)GetValue(AllowExpandProperty); }
set { SetValue(AllowExpandProperty, value); }
}
public Brush HeaderBorderBrush
{
get { return (Brush)GetValue(HeaderBorderBrushProperty); }
set { SetValue(HeaderBorderBrushProperty, value); }
}
public Brush GridLineBrush
{
get { return (Brush)GetValue(GridLineBrushProperty); }
set { SetValue(GridLineBrushProperty, value); }
}
[TypeConverter(typeof(ColumnAlignmentCollectionConverter))]
public Collection<HorizontalAlignment> ColumnAlignments
{
get { return (Collection<HorizontalAlignment>)GetValue(ColumnAlignmentsProperty); }
set { SetValue(ColumnAlignmentsProperty, value); }
}
public GridLength RowHeaderWidth
{
get { return (GridLength)GetValue(RowHeaderWidthProperty); }
set { SetValue(RowHeaderWidthProperty, value); }
}
public GridLength DefaultColumnWidth
{
get { return (GridLength)GetValue(DefaultColumnWidthProperty); }
set { SetValue(DefaultColumnWidthProperty, value); }
}
public Brush AlternatingRowsBackground
{
get { return (Brush)GetValue(AlternatingRowsBackgroundProperty); }
set { SetValue(AlternatingRowsBackgroundProperty, value); }
}
public CellRef AutoFillCell
{
get { return autoFillCell; }
set
{
autoFillCell = (CellRef)CoerceSelectionCell(this, value);
OnSelectedCellsChanged();
}
}
[TypeConverter(typeof(GridLengthCollectionConverter))]
public Collection<GridLength> ColumnWidths
{
get { return (Collection<GridLength>)GetValue(ColumnWidthsProperty); }
set { SetValue(ColumnWidthsProperty, value); }
}
[TypeConverter(typeof(StringCollectionConverter))]
public StringCollection ColumnHeaders
{
get { return (StringCollection)GetValue(ColumnHeadersProperty); }
set { SetValue(ColumnHeadersProperty, value); }
}
[TypeConverter(typeof(StringCollectionConverter))]
public StringCollection FormatStrings
{
get { return (StringCollection)GetValue(FormatStringsProperty); }
set { SetValue(FormatStringsProperty, value); }
}
[TypeConverter(typeof(StringCollectionConverter))]
public StringCollection RowHeaders
{
get { return (StringCollection)GetValue(RowHeadersProperty); }
set { SetValue(RowHeadersProperty, value); }
}
public bool ItemsInColumns
{
get { return (bool)GetValue(ItemsInColumnsProperty); }
set { SetValue(ItemsInColumnsProperty, value); }
}
/// <summary>
/// Gets or sets the content of the grid.
/// </summary>
public object Content
{
get { return GetValue(ContentProperty); }
set { SetValue(ContentProperty, value); }
}
/// <summary>
/// Gets or sets the current cell.
/// </summary>
public CellRef CurrentCell
{
get { return (CellRef)GetValue(CurrentCellProperty); }
set { SetValue(CurrentCellProperty, value); }
}
/// <summary>
/// Gets or sets the cell defining the selection area.
/// The selection area is defined by the CurrentCell and SelectionCell.
/// </summary>
public CellRef SelectionCell
{
get { return (CellRef)GetValue(SelectionCellProperty); }
set { SetValue(SelectionCellProperty, value); }
}
/// <summary>
/// Gets or sets the rows.
/// </summary>
/// <value>The rows.</value>
public int Rows { get; set; }
/// <summary>
/// Gets or sets the columns.
/// </summary>
/// <value>The columns.</value>
public int Columns { get; set; }
[TypeConverter(typeof(StringCollectionConverter))]
public StringCollection DataFields
{
get { return (StringCollection)GetValue(DataFieldsProperty); }
set { SetValue(DataFieldsProperty, value); }
}
public IEnumerable<CellRef> SelectedCells
{
get
{
int rowMin = Math.Min(CurrentCell.Row, SelectionCell.Row);
int columnMin = Math.Min(CurrentCell.Column, SelectionCell.Column);
int rowMax = Math.Max(CurrentCell.Row, SelectionCell.Row);
int columnMax = Math.Max(CurrentCell.Column, SelectionCell.Column);
for (int i = rowMin; i <= rowMax; i++)
{
for (int j = columnMin; j <= columnMax; j++)
{
yield return new CellRef(i, j);
}
}
}
}
public bool AutoSizeColumns
{
get { return (bool)GetValue(AutoSizeColumnsProperty); }
set { SetValue(AutoSizeColumnsProperty, value); }
}
public bool CanInsert
{
get { return (bool)GetValue(CanInsertProperty); }
set { SetValue(CanInsertProperty, value); }
}
public bool CanDelete
{
get { return (bool)GetValue(CanDeleteProperty); }
set { SetValue(CanDeleteProperty, value); }
}
protected virtual bool CanInsertRows
{
get { return !ItemsInColumns && CanInsert && Content is IList && !(Content is Array); }
}
protected virtual bool CanDeleteRows
{
get { return CanDelete && !ItemsInColumns && Content is IList && !(Content is Array); }
}
protected virtual bool CanInsertColumns
{
get { return ItemsInColumns && CanInsert && Content is IList && !(Content is Array); }
}
protected virtual bool CanDeleteColumns
{
get { return CanDelete && ItemsInColumns && Content is IList && !(Content is Array); }
}
public GridLength DefaultRowHeight
{
get { return (GridLength)GetValue(DefaultRowHeightProperty); }
set { SetValue(DefaultRowHeightProperty, value); }
}
protected StringCollection ActualDataFields { get; set; }
protected StringCollection ActualColumnHeaders { get; set; }
public bool CanResizeColumns
{
get { return (bool)GetValue(CanResizeColumnsProperty); }
set { SetValue(CanResizeColumnsProperty, value); }
}
/// <summary>
/// Gets or sets the header used for the add item row/column. Default is "*".
/// </summary>
/// <value>The add item header.</value>
public string AddItemHeader
{
get { return (string)GetValue(AddItemHeaderProperty); }
set { SetValue(AddItemHeaderProperty, value); }
}
[Browsable(false)]
public Collection<TypeDefinition> TypeDefinitions
{
get { return typeDefinitions; }
}
private readonly Collection<TypeDefinition> typeDefinitions = new Collection<TypeDefinition>();
//private static void CurrentItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
//{
// ((SimpleGrid)d).OnCurrentItemChanged(e);
//}
//protected virtual void OnCurrentItemChanged(DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
//{
// int index = GetIndexOfItem(CurrentItem);
// if (index < 0)
// {
// return;
// }
// if (ItemsInColumns)
// {
// if (index < Rows)
// {
// CurrentCell = new CellRef(index, CurrentCell.Column);
// }
// }
// else
// {
// if (index < Columns)
// {
// CurrentCell = new CellRef(CurrentCell.Row, index);
// }
// }
//}
private static object CoerceCurrentCell(DependencyObject d, object basevalue)
{
var cr = (CellRef)basevalue;
int row = cr.Row;
int column = cr.Column;
var sg = (SimpleGrid)d;
row = Clamp(row, 0, sg.Rows - 1);
column = Clamp(column, 0, sg.Columns - 1);
// row = Clamp(row, 0, sg.Rows - 1 + (sg.CanInsertRows ? 1 : 0));
// column = Clamp(column, 0, sg.Columns - 1 + (sg.CanInsertColumns ? 1 : 0));
return new CellRef(row, column);
}
private static object CoerceSelectionCell(DependencyObject d, object basevalue)
{
var cr = (CellRef)basevalue;
int row = cr.Row;
int column = cr.Column;
var sg = (SimpleGrid)d;
row = Clamp(row, 0, sg.Rows - 1);
column = Clamp(column, 0, sg.Columns - 1);
return new CellRef(row, column);
}
private static void ContentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((SimpleGrid)d).OnCellsChanged();
}
private void OnCellsChanged()
{
UpdateGridContent();
}
private static void CurrentCellChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((SimpleGrid)d).OnCurrentCellChanged();
}
private static void SelectionCellChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((SimpleGrid)d).OnSelectionCellChanged();
}
private void OnCurrentCellChanged()
{
OnSelectedCellsChanged();
// CurrentItem = GetItem(CurrentCell);
this.ScrollIntoView(CurrentCell);
// if (CurrentCell.Row >= Rows || CurrentCell.Column >= Columns)
// InsertItem(-1);
}
private void OnSelectionCellChanged()
{
OnSelectedCellsChanged();
this.ScrollIntoView(SelectionCell);
}
private void OnSelectedCellsChanged()
{
if (selection == null)
{
return;
}
{
int row = Math.Min(CurrentCell.Row, SelectionCell.Row);
int column = Math.Min(CurrentCell.Column, SelectionCell.Column);
int rowspan = Math.Abs(CurrentCell.Row - SelectionCell.Row) + 1;
int columnspan = Math.Abs(CurrentCell.Column - SelectionCell.Column) + 1;
Grid.SetRow(selection, row);
Grid.SetColumn(selection, column);
Grid.SetColumnSpan(selection, columnspan);
Grid.SetRowSpan(selection, rowspan);
Grid.SetRow(selectionBackground, row);
Grid.SetColumn(selectionBackground, column);
Grid.SetColumnSpan(selectionBackground, columnspan);
Grid.SetRowSpan(selectionBackground, rowspan);
Grid.SetColumn(columnSelectionBackground, column);
Grid.SetColumnSpan(columnSelectionBackground, columnspan);
Grid.SetRow(rowSelectionBackground, row);
Grid.SetRowSpan(rowSelectionBackground, rowspan);
Grid.SetRow(currentBackground, CurrentCell.Row);
Grid.SetColumn(currentBackground, CurrentCell.Column);
Grid.SetColumn(autoFillBox, column + columnspan - 1);
Grid.SetRow(autoFillBox, row + rowspan - 1);
bool allSelected = rowspan == Rows && columnspan == Columns;
topleft.Background = allSelected ? rowSelectionBackground.Background : rowGrid.Background;
}
{
int row = Math.Min(CurrentCell.Row, AutoFillCell.Row);
int column = Math.Min(CurrentCell.Column, AutoFillCell.Column);
int rowspan = Math.Abs(CurrentCell.Row - AutoFillCell.Row) + 1;
int columnspan = Math.Abs(CurrentCell.Column - AutoFillCell.Column) + 1;
Grid.SetColumn(autoFillSelection, column);
Grid.SetRow(autoFillSelection, row);
Grid.SetColumnSpan(autoFillSelection, columnspan);
Grid.SetRowSpan(autoFillSelection, rowspan);
}
// Debug.WriteLine("OnSelectedCellsChanged\n"+Environment.StackTrace+"\n");
SelectedItems = EnumerateItems(CurrentCell, SelectionCell);
if (!ShowEditor())
{
HideEditor();
}
}
private Collection<ColumnDefinition> columnDefinitions = new Collection<ColumnDefinition>();
public Collection<ColumnDefinition> ColumnDefinitions
{
get { return columnDefinitions; }
}
/// <summary>
/// Gets or sets a value indicating whether this control is using UI virtualizing.
/// When true, only the UIElements of the visible cells will be created.
/// </summary>
public bool IsVirtualizing
{
get { return (bool)GetValue(IsVirtualizingProperty); }
set { SetValue(IsVirtualizingProperty, value); }
}
public static readonly DependencyProperty IsVirtualizingProperty =
DependencyProperty.Register("IsVirtualizing", typeof(bool), typeof(SimpleGrid), new UIPropertyMetadata(false));
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/SimpleGrid/SimpleGrid.Properties.cs | C# | gpl3 | 22,304 |
using System;
namespace PropertyTools.Wpf
{
public class AutoFiller
{
private Func<CellRef, object> GetCellValue;
private Func<CellRef, object, bool> TrySetCellValue;
public AutoFiller(Func<CellRef, object> getCellValue, Func<CellRef, object, bool> trySetCellValue)
{
GetCellValue = getCellValue;
TrySetCellValue = trySetCellValue;
}
public bool TryExtrapolate(CellRef cell, CellRef currentCell, CellRef selectionCell, CellRef autoFillRef, out object result)
{
int selMinRow = Math.Min(currentCell.Row, selectionCell.Row);
int selMaxRow = Math.Max(currentCell.Row, selectionCell.Row);
int selMinCol = Math.Min(currentCell.Column, selectionCell.Column);
int selMaxCol = Math.Max(currentCell.Column, selectionCell.Column);
int i = cell.Row;
int j = cell.Column;
// skip cells inside selection area
if (i >= selMinRow && i <= selMaxRow && j >= selMinCol && j <= selMaxCol)
{
result = null;
return false;
}
object value = null;
if (i < selMinRow)
{
TryExtrapolate(cell, new CellRef(selMinRow, j), new CellRef(selMaxRow, j), out value);
}
if (i > selMaxRow)
{
TryExtrapolate(cell, new CellRef(selMinRow, j), new CellRef(selMaxRow, j), out value);
}
if (j < selMinCol)
{
TryExtrapolate(cell, new CellRef(i, selMinCol), new CellRef(i, selMaxCol), out value);
}
if (j > selMaxCol)
{
TryExtrapolate(cell, new CellRef(i, selMinCol), new CellRef(i, selMaxCol), out value);
}
if (value == null)
{
var source = new CellRef(PeriodicClamp(i, selMinRow, selMaxRow),
PeriodicClamp(j, selMinCol, selMaxCol));
value = GetCellValue(source);
}
if (value != null)
{
result = value;
return true;
}
result = null;
return false;
}
public void AutoFill(CellRef currentCell, CellRef selectionCell, CellRef autoFillRef)
{
for (int i = Math.Min(currentCell.Row, autoFillRef.Row);
i <= Math.Max(currentCell.Row, autoFillRef.Row);
i++)
{
for (int j = Math.Min(currentCell.Column, autoFillRef.Column);
j <= Math.Max(currentCell.Column, autoFillRef.Column);
j++)
{
object value;
var cell = new CellRef(i, j);
if (TryExtrapolate(cell, currentCell, selectionCell, autoFillRef, out value))
{
TrySetCellValue(cell, value);
// UpdateCellContent(cell);
}
}
}
}
/// <summary>
/// Clamps i between i0 and i1.
/// </summary>
/// <param name = "i">The input.</param>
/// <param name = "i0">The minimum value.</param>
/// <param name = "i1">The maximum value.</param>
/// <returns></returns>
private static int PeriodicClamp(int i, int i0, int i1)
{
if (i0 >= i1)
{
return i0;
}
int di = i1 - i0 + 1;
int i2 = (i - (i1 + 1)) % di;
if (i2 < 0)
{
i2 += di;
}
return i0 + i2;
}
private bool TryExtrapolate(CellRef cell, CellRef p1, CellRef p2, out object result)
{
try
{
var v1 = GetCellValue(p1);
var v2 = GetCellValue(p2);
try
{
double d1 = Convert.ToDouble(v1);
double d2 = Convert.ToDouble(v2);
v1 = d1;
v2 = d2;
}
catch (Exception)
{
}
int deltaColumns = p2.Column - p1.Column;
int deltaRows = p2.Row - p1.Row;
double f = 0;
if (cell.Column < p1.Column || cell.Column > p2.Column)
{
if (deltaColumns > 0)
{
f = 1.0 * (cell.Column - p1.Column) / deltaColumns;
}
}
if (cell.Row < p1.Row || cell.Row > p2.Row)
{
if (deltaRows > 0)
{
f = 1.0 * (cell.Row - p1.Row) / deltaRows;
}
}
if (f == 0)
{
result = v1;
return true;
}
object tmp1, tmp2, tmp3;
ReflectionMath.TrySubtract(v2, v1, out tmp1);
ReflectionMath.TryMultiply(tmp1, f, out tmp2);
ReflectionMath.TryAdd(v1, tmp2, out tmp3);
result = tmp3;
return true;
}
catch
{
result = null;
return false;
}
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/SimpleGrid/AutoFiller.cs | C# | gpl3 | 5,672 |
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
namespace PropertyTools.Wpf
{
public class ColumnAlignmentCollectionConverter : TypeConverter
{
private static readonly char[] SplitterChars = ",;".ToCharArray();
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
var s = value as string;
if (s != null)
{
var c = new Collection<HorizontalAlignment>();
foreach (var item in s.Split(SplitterChars))
{
if (!String.IsNullOrEmpty(item))
{
var itemL = item.ToLower();
if (itemL.StartsWith("l"))
{
c.Add(HorizontalAlignment.Left);
continue;
}
if (itemL.StartsWith("r"))
{
c.Add(HorizontalAlignment.Right);
continue;
}
if (itemL.StartsWith("s"))
{
c.Add(HorizontalAlignment.Stretch);
continue;
}
}
c.Add(HorizontalAlignment.Center);
}
return c;
}
return base.ConvertFrom(context, culture, value);
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/SimpleGrid/ColumnAlignmentCollectionConverter.cs | C# | gpl3 | 1,945 |
using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows.Data;
namespace PropertyTools.Wpf
{
[TypeConverter(typeof(CellRefConverter))]
public struct CellRef
{
private int column;
private int row;
public CellRef(int row, int column)
{
this.row = row;
this.column = column;
}
public int Row
{
get { return row; }
set { row = value; }
}
public int Column
{
get { return column; }
set { column = value; }
}
public override string ToString()
{
return String.Format("{0}{1}", ToColumnName(Column), Row + 1);
}
public override int GetHashCode()
{
long hash = column;
hash = (hash << 16)+row;
return (int)hash;
}
public static string ToRowName(int row)
{
return (row + 1).ToString();
}
public static string ToColumnName(int column)
{
string result = string.Empty;
while (column >= 26)
{
int i = column / 26;
result += ((char)('A' + i - 1)).ToString();
column = column - i * 26;
}
result += ((char)('A' + column)).ToString();
return result;
}
}
[ValueConversion(typeof(string), typeof(CellRef))]
public class CellRefConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (targetType == typeof(string) && value != null)
return value.ToString();
if (targetType != typeof(CellRef))
return Binding.DoNothing;
if (value == null)
return new CellRef(0, 0);
var s = value.ToString().ToUpperInvariant();
string sRow = "";
string sColumn = "";
foreach (var c in s)
if (Char.IsDigit(c))
sRow += c;
else
sColumn += c;
int row = int.Parse(sRow) - 1;
int column = 0;
for (int i = sColumn.Length - 1; i >= 0; i--)
column += column * 26 + (int)sColumn[i] - (int)'A';
return new CellRef(row, column);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Convert(value, targetType, parameter, culture);
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/SimpleGrid/CellRef.cs | C# | gpl3 | 2,750 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace PropertyTools.Wpf
{
///<summary>
/// The SimpleGrid is a 'DataGrid' control with a 'spreadsheet style'.
///
/// Supported data sources (set in the Content property)
/// - arrays (rank 1 or 2)
/// - enumerables
/// - lists (supports add, insert and delete)
///
/// Editing of the following types is included
/// - bool
/// - enums
/// - strings
///
/// Custom display/edit templates can be defined in
/// - ColumnDefinitions (these are only used in the defined column)
/// - TypeDefinitions (these are used in any cell)
///
/// Features
/// - fit to width and proportional column widths (using Gridlengths)
/// - autofill
/// - copy/paste
/// - zoom
/// - insert/delete (IList only)
/// - autogenerate columns
///
/// todo:
/// - add item issues
/// - only update modified cells on INPC and INCC
/// - update Content
/// - custom edit/display Templates
///</summary>
[ContentProperty("Content")]
[TemplatePart(Name = PART_SheetScroller, Type = typeof(ScrollViewer))]
[TemplatePart(Name = PART_SheetGrid, Type = typeof(Grid))]
[TemplatePart(Name = PART_ColumnScroller, Type = typeof(ScrollViewer))]
[TemplatePart(Name = PART_ColumnGrid, Type = typeof(Grid))]
[TemplatePart(Name = PART_RowScroller, Type = typeof(ScrollViewer))]
[TemplatePart(Name = PART_RowGrid, Type = typeof(Grid))]
[TemplatePart(Name = PART_SelectionBackground, Type = typeof(Border))]
[TemplatePart(Name = PART_RowSelectionBackground, Type = typeof(Border))]
[TemplatePart(Name = PART_ColumnSelectionBackground, Type = typeof(Border))]
[TemplatePart(Name = PART_CurrentBackground, Type = typeof(Border))]
[TemplatePart(Name = PART_Selection, Type = typeof(Border))]
[TemplatePart(Name = PART_AutoFillSelection, Type = typeof(Border))]
[TemplatePart(Name = PART_AutoFillBox, Type = typeof(Border))]
[TemplatePart(Name = PART_TopLeft, Type = typeof(Border))]
[TemplatePart(Name = PART_TextEditor, Type = typeof(TextBox))]
[TemplatePart(Name = PART_EnumEditor, Type = typeof(ComboBox))]
public partial class SimpleGrid : Control
{
private const string PART_SheetScroller = "PART_SheetScroller";
private const string PART_SheetGrid = "PART_SheetGrid";
private const string PART_ColumnScroller = "PART_ColumnScroller";
private const string PART_ColumnGrid = "PART_ColumnGrid";
private const string PART_RowScroller = "PART_RowScroller";
private const string PART_RowGrid = "PART_RowGrid";
private const string PART_SelectionBackground = "PART_SelectionBackground";
private const string PART_CurrentBackground = "PART_CurrentBackground";
private const string PART_Selection = "PART_Selection";
private const string PART_AutoFillSelection = "PART_AutoFillSelection";
private const string PART_AutoFillBox = "PART_AutoFillBox";
private const string PART_TopLeft = "PART_TopLeft";
private const string PART_TextEditor = "PART_TextEditor";
private const string PART_EnumEditor = "PART_EnumEditor";
private const string PART_ColumnSelectionBackground = "PART_ColumnSelectionBackground";
private const string PART_RowSelectionBackground = "PART_RowSelectionBackground";
private Border autoFillBox;
private CellRef autoFillCell;
private Border autoFillSelection;
private ToolTip autoFillToolTip;
private AutoFiller autoFiller;
private Grid columnGrid;
private ScrollViewer columnScroller;
private Border columnSelectionBackground;
private Border currentBackground;
private IEnumerable<CellRef> editingCells;
private ComboBox enumEditor;
private ContentControl contentEditor;
private bool isCapturing;
private bool isSelectingColumns;
private bool isSelectingRows;
private Grid rowGrid;
private ScrollViewer rowScroller;
private Border rowSelectionBackground;
private Border selection;
private Border selectionBackground;
private Grid sheetGrid;
private ScrollViewer sheetScroller;
private object subcribedContent;
private TextBox textEditor;
private Border topleft;
private bool endPressed;
static SimpleGrid()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(SimpleGrid),
new FrameworkPropertyMetadata(typeof(SimpleGrid)));
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
sheetScroller = Template.FindName(PART_SheetScroller, this) as ScrollViewer;
sheetGrid = Template.FindName(PART_SheetGrid, this) as Grid;
columnScroller = Template.FindName(PART_ColumnScroller, this) as ScrollViewer;
columnGrid = Template.FindName(PART_ColumnGrid, this) as Grid;
rowScroller = Template.FindName(PART_RowScroller, this) as ScrollViewer;
rowGrid = Template.FindName(PART_RowGrid, this) as Grid;
rowSelectionBackground = Template.FindName(PART_RowSelectionBackground, this) as Border;
columnSelectionBackground = Template.FindName(PART_ColumnSelectionBackground, this) as Border;
selectionBackground = Template.FindName(PART_SelectionBackground, this) as Border;
currentBackground = Template.FindName(PART_CurrentBackground, this) as Border;
selection = Template.FindName(PART_Selection, this) as Border;
autoFillSelection = Template.FindName(PART_AutoFillSelection, this) as Border;
autoFillBox = Template.FindName(PART_AutoFillBox, this) as Border;
topleft = Template.FindName(PART_TopLeft, this) as Border;
textEditor = Template.FindName(PART_TextEditor, this) as TextBox;
enumEditor = Template.FindName(PART_EnumEditor, this) as ComboBox;
contentEditor = new ContentControl();
enumEditor.SelectionChanged += EnumEditorSelectionChanged;
textEditor.PreviewKeyDown += TextEditorPreviewKeyDown;
textEditor.LostFocus += TextEditorLostFocus;
sheetScroller.ScrollChanged += ScrollViewerScrollChanged;
rowScroller.ScrollChanged += RowScrollerChanged;
columnScroller.ScrollChanged += ColumnScrollerChanged;
sheetScroller.SizeChanged += ScrollViewerSizeChanged;
topleft.MouseLeftButtonDown += TopleftMouseLeftButtonDown;
autoFillBox.MouseLeftButtonDown += AutoFillBoxMouseLeftButtonDown;
columnGrid.MouseLeftButtonDown += ColumnGridMouseLeftButtonDown;
columnGrid.MouseMove += ColumnGridMouseMove;
columnGrid.MouseLeftButtonUp += ColumnGridMouseLeftButtonUp;
columnGrid.Loaded += ColumnGridLoaded;
sheetGrid.SizeChanged += ColumnGridSizeChanged;
rowGrid.MouseLeftButtonDown += RowGridMouseLeftButtonDown;
rowGrid.MouseMove += RowGridMouseMove;
rowGrid.MouseLeftButtonUp += RowGridMouseLeftButtonUp;
Focusable = true;
autoFiller = new AutoFiller(GetCellValue, TrySetCellValue);
autoFillToolTip = new ToolTip { Placement = PlacementMode.Bottom, PlacementTarget = autoFillSelection };
UpdateGridContent();
OnSelectedCellsChanged();
BuildContextMenus();
CommandBindings.Add(new CommandBinding(ApplicationCommands.Copy, CopyExecute));
CommandBindings.Add(new CommandBinding(ApplicationCommands.Cut, CutExecute));
CommandBindings.Add(new CommandBinding(ApplicationCommands.Paste, PasteExecute));
CommandBindings.Add(new CommandBinding(ApplicationCommands.Delete, DeleteExecute));
}
/// <summary>
/// Gets the index of the specified item in the Content enumerable.
/// </summary>
/// <param name="item">The item.</param>
/// <returns></returns>
protected int GetIndexOfItem(object item)
{
var list = Content as IEnumerable;
if (list != null)
{
int i = 0;
foreach (var listItem in list)
{
if (listItem == item)
{
return i;
}
i++;
}
}
return -1;
}
//protected int GetIndexOfProperty(string propertyName)
//{
// if (DataFields == null)
// {
// return -1;
// }
// for (int i = 0; i < DataFields.Count; i++)
// {
// if (DataFields[i] == propertyName)
// {
// return i;
// }
// }
// return -1;
//}
private static int Clamp(int value, int min, int max)
{
int result = value;
if (result > max)
{
result = max;
}
if (result < min)
{
result = min;
}
return result;
}
/// <summary>
/// Enumerate the items in the specified cell range.
/// This is used to updated the SelectedItems property.
/// </summary>
private IEnumerable EnumerateItems(CellRef cell0, CellRef cell1)
{
if (!(Content is Array))
{
var list = Content as IList;
if (list != null)
{
int index0 = !ItemsInColumns ? cell0.Row : cell0.Column;
int index1 = !ItemsInColumns ? cell1.Row : cell1.Column;
int min = Math.Min(index0, index1);
int max = Math.Max(index0, index1);
for (int index = min; index <= max; index++)
{
if (index >= 0 && index < list.Count)
{
yield return list[index];
}
}
}
}
}
private object GetItem(CellRef cell)
{
if (Content is Array)
{
return null;
}
var list = Content as IList;
if (list != null)
{
int index = GetItemIndex(cell);
if (index >= 0 && index < list.Count)
{
return list[index];
}
}
var items = Content as IEnumerable;
if (items != null)
{
int i = 0;
foreach (var item in items)
{
if ((!ItemsInColumns && i == cell.Row) || (!!ItemsInColumns && i == cell.Column))
{
return item;
}
i++;
}
}
return null;
}
private static void SetElementPosition(UIElement element, CellRef cell)
{
Grid.SetColumn(element, cell.Column);
Grid.SetRow(element, cell.Row);
}
/// <summary>
/// Gets the alternative values for the cell.
/// </summary>
/// <param name="cell">The cell.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
protected virtual IEnumerable GetCellAlternatives(CellRef cell, object value)
{
if (value == null)
value = GetCellValue(cell);
var enumValue = value as Enum;
if (enumValue != null)
{
return Enum.GetValues(enumValue.GetType());
}
return null;
}
public bool ShowEditor()
{
var value = GetCellValue(CurrentCell);
if (value is Enum)
return ShowComboBoxEditor();
if (value != null)
{
var type = value.GetType();
DataTemplate template = null;
var cd = GetColumnDefinition(CurrentCell);
if (cd != null && cd.EditTemplate != null)
{
template = cd.EditTemplate;
contentEditor.Content = GetItem(CurrentCell);
}
if (template == null)
{
template = GetEditTemplate(type);
contentEditor.Content = GetCellValue(CurrentCell);
}
if (template != null)
{
contentEditor.ContentTemplate = template;
SetElementPosition(contentEditor, CurrentCell);
contentEditor.Visibility = Visibility.Visible;
return true;
}
}
return false;
}
public void HideEditor()
{
contentEditor.Visibility = Visibility.Hidden;
enumEditor.Visibility = Visibility.Hidden;
}
public void ShowTextBoxEditor()
{
editingCells = SelectedCells.ToList();
Grid.SetColumn(textEditor, CurrentCell.Column);
Grid.SetRow(textEditor, CurrentCell.Row);
textEditor.Text = GetCellString(CurrentCell);
textEditor.TextAlignment = ToTextAlignment(GetHorizontalAlignment(CurrentCell));
textEditor.Visibility = Visibility.Visible;
textEditor.Focus();
textEditor.CaretIndex = textEditor.Text.Length;
textEditor.SelectAll();
}
/// <summary>
/// Convert a HorizontalAlignment to a TextAlignment.
/// </summary>
private static TextAlignment ToTextAlignment(HorizontalAlignment a)
{
switch (a)
{
case HorizontalAlignment.Left:
return TextAlignment.Left;
case HorizontalAlignment.Center:
return TextAlignment.Center;
case HorizontalAlignment.Right:
return TextAlignment.Right;
default:
return TextAlignment.Left;
}
}
public bool ShowComboBoxEditor()
{
var value = GetCellValue(CurrentCell);
var alternatives = GetCellAlternatives(CurrentCell, value);
if (alternatives == null)
{
return false;
}
SetElementPosition(enumEditor, CurrentCell);
// set editingCells to null to avoid setting values when enumEditor.SelectedValue is set below
editingCells = null;
enumEditor.ItemsSource = alternatives;
enumEditor.SelectedValue = value;
enumEditor.Visibility = Visibility.Visible;
editingCells = SelectedCells.ToList();
return true;
}
private void EnumEditorSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (editingCells == null)
{
return;
}
foreach (var cell in editingCells)
{
TrySetCellValue(cell, enumEditor.SelectedValue);
}
}
private bool SetCheckInSelectedCells(bool value)
{
bool modified = false;
foreach (var cell in SelectedCells)
{
var currentValue = GetCellValue(cell);
if (currentValue is bool)
{
if (TrySetCellValue(cell, value))
modified = true;
}
}
return modified;
}
private bool ToggleCheckInSelectedCells()
{
bool modified = false;
foreach (var cell in SelectedCells)
{
var currentValue = GetCellValue(cell);
if (currentValue is bool)
{
if (TrySetCellValue(cell, !((bool)currentValue)))
modified = true;
}
}
return modified;
}
public void EndTextEdit()
{
if (textEditor.Visibility == Visibility.Hidden)
{
return;
}
foreach (var cell in editingCells)
{
TrySetCellValue(cell, textEditor.Text);
}
textEditor.Visibility = Visibility.Hidden;
}
public void CancelTextEdit()
{
textEditor.Visibility = Visibility.Hidden;
}
private void BuildContextMenus()
{
var rowsMenu = new ContextMenu();
if (CanInsertRows)
{
rowsMenu.Items.Add(new MenuItem { Header = "Insert", Command = new DelegateCommand(InsertRows) });
}
if (CanDeleteRows)
{
rowsMenu.Items.Add(new MenuItem { Header = "Delete", Command = new DelegateCommand(DeleteRows) });
}
if (rowsMenu.Items.Count > 0)
{
rowGrid.ContextMenu = rowsMenu;
}
var columnsMenu = new ContextMenu();
if (CanInsertColumns)
{
columnsMenu.Items.Add(new MenuItem { Header = "Insert" });
}
if (CanDeleteColumns)
{
columnsMenu.Items.Add(new MenuItem { Header = "Delete" });
}
if (columnsMenu.Items.Count > 0)
{
columnGrid.ContextMenu = columnsMenu;
}
}
public void Paste()
{
if (!Clipboard.ContainsText())
{
return;
}
string text = Clipboard.GetText().Trim();
var textArray = TextToArray(text);
int rowMin = Math.Min(CurrentCell.Row, SelectionCell.Row);
int columnMin = Math.Min(CurrentCell.Column, SelectionCell.Column);
int rowMax = Math.Max(CurrentCell.Row, SelectionCell.Row);
int columnMax = Math.Max(CurrentCell.Column, SelectionCell.Column);
int rows = textArray.GetUpperBound(0) + 1;
int columns = textArray.GetUpperBound(1) + 1;
for (int i = rowMin; i <= rowMax || i < rowMin + rows; i++)
{
if (i >= Rows)
{
if (!InsertItem(-1))
{
break;
}
}
for (int j = columnMin; j <= columnMax || j < columnMin + columns; j++)
{
string value =
textArray[(i - rowMin) % rows, (j - columnMin) % columns];
TrySetCellValue(new CellRef(i, j), value);
}
}
CurrentCell = new CellRef(rowMin, columnMin);
SelectionCell = new CellRef(Math.Max(rowMax, rowMin + rows - 1),
Math.Max(columnMax, columnMin + columns - 1));
}
public void Copy()
{
Copy("\t");
}
public void Copy(string separator)
{
var text = SelectionToString(separator);
Clipboard.SetText(text);
}
public string ToCsv(string separator = ";")
{
var sb = new StringBuilder();
for (int j = 0; j < Columns; j++)
{
var h = GetColumnHeader(j).ToString();
h = CsvEncodeString(h);
if (sb.Length > 0) sb.Append(separator);
sb.Append(h);
}
sb.AppendLine();
sb.Append(SheetToString(";", true));
return sb.ToString();
}
private string SelectionToString(string separator, bool encode = false)
{
return ToString(CurrentCell, SelectionCell, separator, encode);
}
private string SheetToString(string separator, bool encode = false)
{
return ToString(new CellRef(0, 0), new CellRef(Rows - 1, Columns - 1), separator, encode);
}
private string ToString(CellRef cell1, CellRef cell2, string separator, bool encode = false)
{
int rowMin = Math.Min(cell1.Row, cell2.Row);
int columnMin = Math.Min(cell1.Column, cell2.Column);
int rowMax = Math.Max(cell1.Row, cell2.Row);
int columnMax = Math.Max(cell1.Column, cell2.Column);
var sb = new StringBuilder();
for (int i = rowMin; i <= rowMax; i++)
{
if (i > rowMin)
{
sb.AppendLine();
}
for (int j = columnMin; j <= columnMax; j++)
{
string cell = GetCellString(new CellRef(i, j));
if (encode)
cell = CsvEncodeString(cell);
if (j > columnMin)
{
sb.Append(separator);
}
if (cell != null)
{
sb.Append(cell);
}
}
}
return sb.ToString();
}
private static string CsvEncodeString(string cell)
{
cell = cell.Replace("\"", "\"\"");
if (cell.Contains(";") || cell.Contains("\""))
cell = "\"" + cell + "\"";
return cell;
}
private void Delete()
{
foreach (var cell in SelectedCells)
{
TrySetCellValue(cell, null);
}
}
private void InsertRows()
{
int from = Math.Min(CurrentCell.Row, SelectionCell.Row);
int to = Math.Max(CurrentCell.Row, SelectionCell.Row);
for (int i = 0; i < to - from + 1; i++)
{
InsertItem(from, false);
}
UpdateGridContent();
}
private void DeleteRows()
{
int from = Math.Min(CurrentCell.Row, SelectionCell.Row);
int to = Math.Max(CurrentCell.Row, SelectionCell.Row);
for (int i = to; i >= from; i--)
{
DeleteItem(i, false);
}
UpdateGridContent();
int maxRow = Rows > 0 ? Rows - 1 : 0;
if (CurrentCell.Row > maxRow)
{
CurrentCell = new CellRef(maxRow, CurrentCell.Column);
}
if (SelectionCell.Row > maxRow)
{
SelectionCell = new CellRef(maxRow, SelectionCell.Column);
}
}
private void ColumnGridSizeChanged(object sender, SizeChangedEventArgs e)
{
UpdateColumnWidths();
}
private void ColumnGridLoaded(object sender, RoutedEventArgs e)
{
UpdateColumnWidths();
}
private void AutoFillBoxMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
// Show the autofill selection border
autoFillSelection.Visibility = Visibility.Visible;
}
private void TextEditorLostFocus(object sender, RoutedEventArgs e)
{
EndTextEdit();
}
private void TextEditorPreviewKeyDown(object sender, KeyEventArgs e)
{
bool shift = Keyboard.IsKeyDown(Key.LeftShift);
switch (e.Key)
{
case Key.Left:
if (textEditor.CaretIndex == 0)
{
EndTextEdit();
OnKeyDown(e);
e.Handled = true;
}
break;
case Key.Right:
if (textEditor.CaretIndex == textEditor.Text.Length)
{
EndTextEdit();
OnKeyDown(e);
e.Handled = true;
}
break;
case Key.Down:
case Key.Up:
EndTextEdit();
OnKeyDown(e);
e.Handled = true;
break;
case Key.Enter:
EndTextEdit();
MoveCurrentCell(shift ? -1 : 1, 0);
e.Handled = true;
break;
case Key.Escape:
CancelTextEdit();
e.Handled = true;
break;
}
}
private void DeleteExecute(object sender, ExecutedRoutedEventArgs e)
{
Delete();
}
private void RowGridMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
int row = GetCell(e.GetPosition(rowGrid)).Row;
if (row >= 0)
{
if (Keyboard.IsKeyDown(Key.LeftShift))
{
CurrentCell = new CellRef(CurrentCell.Row, 0);
}
else
{
CurrentCell = new CellRef(row, 0);
}
SelectionCell = new CellRef(row, Columns - 1);
e.Handled = true;
}
isSelectingRows = true;
rowGrid.CaptureMouse();
}
private void RowGridMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
rowGrid.ReleaseMouseCapture();
isSelectingRows = false;
}
private void RowGridMouseMove(object sender, MouseEventArgs e)
{
if (!isSelectingRows)
{
return;
}
int row = GetCell(e.GetPosition(rowGrid)).Row;
if (row >= 0)
{
SelectionCell = new CellRef(row, Columns - 1);
e.Handled = true;
}
}
private void ColumnGridMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
int column = GetCell(e.GetPosition(columnGrid)).Column;
if (column >= 0)
{
if (Keyboard.IsKeyDown(Key.LeftShift))
{
CurrentCell = new CellRef(0, CurrentCell.Column);
}
else
{
CurrentCell = new CellRef(0, column);
}
SelectionCell = new CellRef(Rows - 1, column);
e.Handled = true;
}
isSelectingColumns = true;
}
private void ColumnGridMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
columnGrid.ReleaseMouseCapture();
isSelectingColumns = false;
}
private void ColumnGridMouseMove(object sender, MouseEventArgs e)
{
if (!isSelectingColumns)
{
return;
}
int column = GetCell(e.GetPosition(columnGrid)).Column;
if (column >= 0)
{
SelectionCell = new CellRef(Rows - 1, column);
e.Handled = true;
}
}
private void TopleftMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
CurrentCell = new CellRef(0, 0);
SelectionCell = new CellRef(Rows - 1, Columns - 1);
e.Handled = true;
}
private void CutExecute(object sender, ExecutedRoutedEventArgs e)
{
Copy();
Delete();
}
private void PasteExecute(object sender, ExecutedRoutedEventArgs e)
{
Paste();
}
private void CopyExecute(object sender, ExecutedRoutedEventArgs e)
{
Copy();
}
private static string[,] TextToArray(string text)
{
int rows = 0;
int columns = 0;
var lines = text.Split('\n');
foreach (string line in lines)
{
rows++;
var fields = line.Split('\t');
if (fields.Length > columns)
{
columns = fields.Length;
}
}
if (rows == 0 || columns == 0)
{
return null;
}
var result = new string[rows, columns];
int row = 0;
foreach (string line in lines)
{
var fields = line.Split('\t');
int column = 0;
foreach (string field in fields)
{
result[row, column] = field.Trim(" \r\n\t".ToCharArray());
column++;
}
row++;
}
return result;
}
private Binding CreateBinding(CellRef cellRef, object value)
{
var dataField = GetDataField(cellRef);
if (dataField != null)
return new Binding(dataField) { StringFormat = GetFormatString(cellRef, value) };
return null;
}
protected bool IsCellVisible(CellRef cell)
{
if (IsVirtualizing)
{
// todo: should store topleft and bottomright visible cells
// and check against these
}
return true;
}
protected void UpdateAllCells()
{
foreach (var element in cellMap.Values)
{
var cell = GetCellRefFromUIElement(element);
UpdateCellContent(cell);
}
}
private CellRef GetCellRefFromUIElement(UIElement element)
{
int row = Grid.GetRow(element);
int column = Grid.GetColumn(element);
return new CellRef(row, column);
}
/// <summary>
/// Virtualizes the UIElements for the visible cells.
/// Adds elements for the visible cells not currently in the logical tree.
/// Removes elements for the nonvisible cells.
/// </summary>
protected void VirtualizeCells()
{
CellRef cell1, cell2;
GetVisibleCells(out cell1, out cell2);
if (cell1.Column < 0)
return;
var delete = cellMap.Keys.ToList();
for (int i = cell1.Row; i <= cell2.Row; i++)
{
for (int j = cell1.Column; j <= cell2.Column; j++)
{
var cellRef = new CellRef(i, j);
var c = GetCellElement(cellRef);
if (c == null)
{
// The cell is not currently in the collection - add it
UpdateCellContent(cellRef);
}
else
{
// the cell is currently in the collection - keep it (remove it from the delete keys)
delete.Remove(cellRef.GetHashCode());
}
}
}
foreach (var hash in delete)
{
var cell = cellMap[hash];
sheetGrid.Children.Remove(cell);
cellInsertionIndex--;
cellMap.Remove(hash);
}
}
protected void UpdateCellContent(CellRef cellRef)
{
var c = GetCellElement(cellRef);
var value = GetCellValue(cellRef);
if (c != null)
{
sheetGrid.Children.Remove(c);
cellInsertionIndex--;
cellMap.Remove(cellRef.GetHashCode());
}
InsertCellElement(cellRef, value, true);
}
readonly Dictionary<int, UIElement> cellMap = new Dictionary<int, UIElement>();
private int cellInsertionIndex;
private void AddCellElement(CellRef cellRef, object value)
{
InsertCellElement(cellRef, value, false);
}
private void InsertCellElement(CellRef cellRef, object value, bool insert)
{
//if (value == null)
// return;
var e = CreateElement(cellRef, null);
SetElementPosition(e, cellRef);
if (insert)
{
sheetGrid.Children.Insert(cellInsertionIndex, e);
cellInsertionIndex++;
}
else
{
sheetGrid.Children.Add(e);
}
cellMap.Add(cellRef.GetHashCode(), e);
}
public UIElement GetCellElement(CellRef cellRef)
{
UIElement e;
return cellMap.TryGetValue(cellRef.GetHashCode(), out e) ? e : null;
}
private object GetColumnHeader(int j)
{
var text = CellRef.ToColumnName(j);
if (!ItemsInColumns)
{
if (j < ColumnDefinitions.Count)
return ColumnDefinitions[j].Header;
if (ActualColumnHeaders != null && j < ActualColumnHeaders.Count)
{
text = ActualColumnHeaders[j];
}
}
return text;
}
private object GetRowHeader(int j)
{
var text = CellRef.ToRowName(j);
if (ItemsInColumns)
{
if (j < ColumnDefinitions.Count)
return ColumnDefinitions[j].Header;
if (ActualColumnHeaders != null && j < ActualColumnHeaders.Count)
{
text = ActualColumnHeaders[j];
}
}
return text;
}
private int GetItemIndex(CellRef cell)
{
return !ItemsInColumns ? cell.Row : cell.Column;
}
private int GetFieldIndex(CellRef cell)
{
return !ItemsInColumns ? cell.Column : cell.Row;
}
private string GetDataField(CellRef cell)
{
int fieldIndex = GetFieldIndex(cell);
if (fieldIndex < ColumnDefinitions.Count)
return ColumnDefinitions[fieldIndex].DataField;
if (ActualDataFields != null && fieldIndex < ActualDataFields.Count)
return ActualDataFields[fieldIndex];
return null;
}
public string GetCellString(CellRef cell)
{
var value = GetCellValue(cell);
if (value == null)
return null;
var formatString = GetFormatString(cell, value);
return FormatValue(value, formatString);
}
/// <summary>
/// Gets the cell value from the Content property for the specified cell.
/// </summary>
/// <param name = "cell">The cell reference.</param>
/// <returns></returns>
public object GetCellValue(CellRef cell)
{
if (cell.Column < 0 || cell.Column >= Columns || cell.Row < 0 || cell.Row >= Rows)
{
return null;
}
if (Content.GetType().IsArray)
{
var cells = (Array)Content;
int rank = cells.Rank;
var value = rank > 1 ? cells.GetValue(cell.Row, cell.Column) : cells.GetValue(cell.Row);
return value;
}
var item = GetItem(cell);
if (item != null)
{
var type = item.GetType();
var dataField = GetDataField(cell);
if (dataField != null)
{
var pi = type.GetProperty(dataField);
if (pi == null)
{
return item;
}
return pi.GetValue(item, null);
}
}
return null;
}
/// <summary>
/// Updates all the UIElements of the grid (both cells, headers, row and column lines).
/// </summary>
private void UpdateGridContent()
{
UnsubscribeNotifications();
if (sheetGrid == null)
{
// return if the template has not yet been applied
return;
}
Array cells = null;
int rows = -1;
int columns = -1;
// Array
if (Content != null && Content.GetType().IsArray)
{
cells = (Array)Content;
int rank = cells.Rank;
rows = cells.GetUpperBound(0) + 1;
columns = rank > 1 ? cells.GetUpperBound(1) + 1 : 1;
}
if (cells == null)
{
var items = Content as IEnumerable;
if (items != null)
{
int n = items.Cast<object>().Count();
int m = 0;
if (UseColumnDefinitions)
{
m = ColumnDefinitions.Count;
}
else
{
var actualDataFields = DataFields;
var actualColumnHeaders = ColumnHeaders;
if (actualDataFields == null)
{
AutoGenerateColumns(items, out actualDataFields, out actualColumnHeaders);
}
ActualDataFields = actualDataFields;
ActualColumnHeaders = actualColumnHeaders;
m = ActualDataFields.Count;
}
rows = !ItemsInColumns ? n : m;
columns = !ItemsInColumns ? m : n;
}
}
// Hide the row/column headers if the content is empty
rowScroller.Visibility = columnScroller.Visibility = sheetScroller.Visibility = topleft.Visibility = rows >= 0 ? Visibility.Visible : Visibility.Hidden;
if (rows < 0)
{
return;
}
//int rank = cells.Rank;
//int rows = cells.GetUpperBound(0) + 1;
//int columns = rank > 1 ? cells.GetUpperBound(1) + 1 : 1;
UpdateRows(rows);
UpdateColumns(columns);
UpdateSheet(rows, columns);
UpdateColumnWidths();
SubscribeNotifications();
}
protected bool UseColumnDefinitions
{
get { return ColumnDefinitions.Count > 0; }
}
private void SubscribeNotifications()
{
var ncc = Content as INotifyCollectionChanged;
if (ncc != null)
{
ncc.CollectionChanged += OnContentCollectionChanged;
}
var items = Content as IEnumerable;
if (items != null)
{
foreach (var item in items)
{
var npc = item as INotifyPropertyChanged;
if (npc != null)
{
npc.PropertyChanged += OnContentItemPropertyChanged;
}
}
}
subcribedContent = Content;
}
private void UnsubscribeNotifications()
{
var ncc = subcribedContent as INotifyCollectionChanged;
if (ncc != null)
{
ncc.CollectionChanged -= OnContentCollectionChanged;
}
var items = subcribedContent as IEnumerable;
if (items != null)
{
foreach (var item in items)
{
var npc = item as INotifyPropertyChanged;
if (npc != null)
{
npc.PropertyChanged -= OnContentItemPropertyChanged;
}
}
}
subcribedContent = null;
}
/// <summary>
/// Called when any item in the Content is changed.
/// </summary>
private void OnContentItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
foreach (var cell in EnumerateCells(sender, e.PropertyName))
{
if (IsCellVisible(cell))
UpdateCellContent(cell);
}
}
private IEnumerable<CellRef> EnumerateCells(object item, string propertyName)
{
if (ActualDataFields == null)
yield break;
if (Content is IEnumerable)
{
int i = 0;
foreach (var it in Content as IEnumerable)
{
if (it == item)
{
for (int j = 0; j < ActualDataFields.Count; j++)
if (ActualDataFields[j] == propertyName)
{
var cell = !ItemsInColumns ? new CellRef(i, j) : new CellRef(j, i);
yield return cell;
}
}
i++;
}
}
}
private void OnContentCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
// todo: update rows
UpdateGridContent();
}
public void AutoSizeAllColumns()
{
sheetGrid.UpdateLayout();
for (int i = 0; i < Columns; i++)
{
AutoSizeColumn(i);
}
}
private void UpdateColumnWidths()
{
sheetGrid.UpdateLayout();
for (int i = 0; i < Columns; i++)
{
if (GetColumnWidth(i) == GridLength.Auto || AutoSizeColumns)
AutoSizeColumn(i);
}
sheetGrid.UpdateLayout();
for (int j = 0; j < sheetGrid.ColumnDefinitions.Count; j++)
{
columnGrid.ColumnDefinitions[j].Width = new GridLength(sheetGrid.ColumnDefinitions[j].ActualWidth);
}
}
private void UpdateSheet(int rows, int columns)
{
//int rank = cells.Rank;
//int rows = cells.GetUpperBound(0) + 1;
//int columns = rank > 1 ? cells.GetUpperBound(1) + 1 : 1;
sheetGrid.Children.Clear();
sheetGrid.Children.Add(selectionBackground);
sheetGrid.Children.Add(currentBackground);
cellMap.Clear();
// todo: UI virtualize grid lines (both rows and columns)
// Add row lines to the sheet
for (int i = 1; i <= rows; i++)
{
var border = new Border
{
BorderBrush = GridLineBrush,
BorderThickness = new Thickness(0, 1, 0, 0)
};
if (i < rows && AlternatingRowsBackground != null && i % 2 == 1)
{
border.Background = AlternatingRowsBackground;
}
Grid.SetColumn(border, 0);
if (columns > 0)
Grid.SetColumnSpan(border, columns);
Grid.SetRow(border, i);
sheetGrid.Children.Add(border);
}
if (rows > 0)
{
// Add column lines to the sheet
for (int i = 0; i < columns; i++)
{
if (i == 0 && columns > 1)
{
continue;
}
var border = new Border
{
BorderBrush = GridLineBrush,
BorderThickness = new Thickness(i > 0 ? 1 : 0, 0, i == columns - 1 ? 1 : 0, 0)
};
Grid.SetRow(border, 0);
Grid.SetRowSpan(border, rows);
Grid.SetColumn(border, i);
sheetGrid.Children.Add(border);
}
}
cellInsertionIndex = sheetGrid.Children.Count;
if (IsVirtualizing)
{
VirtualizeCells();
}
else
{
// Add all cells to the sheet
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
var cell = new CellRef(i, j);
var value = GetCellValue(cell);
AddCellElement(cell, value);
}
}
}
sheetGrid.Children.Add(textEditor);
sheetGrid.Children.Add(selection);
sheetGrid.Children.Add(autoFillBox);
sheetGrid.Children.Add(autoFillSelection);
sheetGrid.Children.Add(contentEditor);
sheetGrid.Children.Add(enumEditor);
}
private void UpdateRows(int rows)
{
rowGrid.RowDefinitions.Clear();
sheetGrid.RowDefinitions.Clear();
rowGrid.Children.Clear();
rowGrid.Children.Add(rowSelectionBackground);
Rows = rows;
for (int i = 0; i < rows; i++)
{
sheetGrid.RowDefinitions.Add(new RowDefinition { Height = DefaultRowHeight });
rowGrid.RowDefinitions.Add(new RowDefinition { Height = DefaultRowHeight });
}
for (int i = 0; i < rows; i++)
{
object header = GetRowHeader(i);
var border = new Border
{
BorderBrush = HeaderBorderBrush,
BorderThickness = new Thickness(1, 0, 1, 1),
Margin = new Thickness(0, 0, 0, -1)
};
Grid.SetRow(border, i);
rowGrid.Children.Add(border);
var cell = header as FrameworkElement;
if (cell == null)
{
cell = new TextBlock
{
Text = header != null ? header.ToString() : "-",
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center,
Padding = new Thickness(4, 2, 4, 2)
};
}
Grid.SetRow(cell, i);
rowGrid.Children.Add(cell);
}
// Add "Insert" row header
if (CanInsertRows && AddItemHeader != null)
{
sheetGrid.RowDefinitions.Add(new RowDefinition { Height = DefaultRowHeight });
rowGrid.RowDefinitions.Add(new RowDefinition { Height = DefaultRowHeight });
var cell = new TextBlock
{
Text = AddItemHeader,
// ToolTip = "Add row",
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center
};
var border = new Border
{
Background = Brushes.Transparent,
BorderBrush = HeaderBorderBrush,
BorderThickness = new Thickness(1, 0, 1, 1),
Margin = new Thickness(0, 0, 0, 0)
};
border.MouseLeftButtonDown += addItemCell_MouseLeftButtonDown;
Grid.SetRow(border, rows);
cell.Padding = new Thickness(4, 2, 4, 2);
Grid.SetRow(cell, rows);
rowGrid.Children.Add(cell);
rowGrid.Children.Add(border);
}
else
{
sheetGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
rowGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
}
// to cover a posisble scrollbar
rowGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(20) });
}
private void UpdateColumns(int columns)
{
Columns = columns;
rowGrid.ColumnDefinitions.Clear();
sheetGrid.ColumnDefinitions.Clear();
for (int i = 0; i < columns; i++)
{
var w = GetColumnWidth(i);
sheetGrid.ColumnDefinitions.Add(new System.Windows.Controls.ColumnDefinition { Width = w });
// the width of the header column will be updated later
columnGrid.ColumnDefinitions.Add(new System.Windows.Controls.ColumnDefinition());
}
// Add one empty column covering the vertical scrollbar
columnGrid.ColumnDefinitions.Add(new System.Windows.Controls.ColumnDefinition { Width = new GridLength(40) });
columnGrid.Children.Clear();
columnGrid.Children.Add(columnSelectionBackground);
for (int j = 0; j < columns; j++)
{
object header = GetColumnHeader(j);
var border = new Border
{
BorderBrush = HeaderBorderBrush,
BorderThickness = new Thickness(0, 1, 1, 1),
Margin = new Thickness(0, 0, j < columns - 1 ? -1 : 0, 0)
};
Grid.SetColumn(border, j);
columnGrid.Children.Add(border);
var cell = header as FrameworkElement;
if (cell == null)
{
cell = new TextBlock
{
Text = header != null ? header.ToString() : "-",
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = GetHorizontalAlignment(new CellRef(!ItemsInColumns ? -1 : j, !ItemsInColumns ? j : -1)),
Padding = new Thickness(4, 2, 4, 2)
};
}
Grid.SetColumn(cell, j);
columnGrid.Children.Add(cell);
if (CanResizeColumns)
{
var splitter = new GridSplitter
{
ResizeDirection = GridResizeDirection.Columns,
Background = Brushes.Transparent,
Width = 4,
Focusable = false,
VerticalAlignment = VerticalAlignment.Stretch,
HorizontalAlignment = HorizontalAlignment.Right
};
splitter.MouseDoubleClick += ColumnSplitterDoubleClick;
splitter.DragStarted += ColumnSplitterChangeStarted;
splitter.DragDelta += ColumnSplitterChangeDelta;
splitter.DragCompleted += ColumnSplitterChangeCompleted;
Grid.SetColumn(splitter, j);
columnGrid.Children.Add(splitter);
}
}
}
protected virtual UIElement CreateElement(CellRef cell, object item = null)
{
FrameworkElement element = null;
if (item == null)
item = GetItem(cell);
var cd = GetColumnDefinition(cell);
if (cd != null && cd.DisplayTemplate != null)
{
element = new ContentControl { ContentTemplate = cd.DisplayTemplate, Content = item };
// note: vertical/horziontal alignment must be set in the DataTemplate
}
if (element == null)
{
var value = GetCellValue(cell);
var type = value != null ? value.GetType() : null;
var template = GetDisplayTemplate(type);
if (template != null)
{
element = new ContentControl { ContentTemplate = template, Content = value };
}
var binding = CreateBinding(cell, value);
if (element == null && type == typeof(bool))
{
var chkbox = new CheckBox { Cursor = Cursors.Arrow };
if (binding != null)
{
chkbox.SetBinding(ToggleButton.IsCheckedProperty, binding);
}
else
{
chkbox.IsChecked = (bool)value;
chkbox.Checked += CellChecked;
}
element = chkbox;
}
if (element == null && typeof(BitmapSource).IsAssignableFrom(type))
{
var chkbox = new Image
{
Source = (BitmapSource)value,
Stretch = Stretch.None
};
element = chkbox;
}
//if (element == null && typeof(Uri).IsAssignableFrom(type))
//{
// element = new TextBlock(new Hyperlink(new Run(value != null ? value.ToString() : null)) { NavigateUri = (Uri)value });
//}
if (element == null)
{
var textBlock = new TextBlock
{
Margin = new Thickness(4, 0, 4, 0),
Foreground = this.Foreground
};
if (binding != null)
{
textBlock.SetBinding(TextBlock.TextProperty, binding);
}
else
{
var formatString = GetFormatString(cell, value);
var text = FormatValue(value, formatString);
textBlock.Text = text;
}
element = textBlock;
}
element.Tag = type;
if (binding != null)
element.DataContext = item;
element.VerticalAlignment = VerticalAlignment.Center;
element.HorizontalAlignment = GetHorizontalAlignment(cell);
}
return element;
}
private ColumnDefinition GetColumnDefinition(CellRef cell)
{
int fieldIndex = GetFieldIndex(cell);
if (fieldIndex < ColumnDefinitions.Count)
return ColumnDefinitions[fieldIndex];
return null;
}
private TypeDefinition GetCustomTemplate(Type type)
{
foreach (var e in TypeDefinitions)
{
var et = e.Type;
if (et.IsAssignableFrom(type))
{
return e;
}
}
return null;
}
private DataTemplate GetDisplayTemplate(Type type)
{
var e = GetCustomTemplate(type);
return e != null ? e.DisplayTemplate : null;
}
private DataTemplate GetEditTemplate(Type type)
{
var e = GetCustomTemplate(type);
return e != null ? e.EditTemplate : null;
}
private static string FormatValue(object value, string formatString)
{
if (String.IsNullOrEmpty(formatString))
{
return value != null ? value.ToString() : null;
}
else
{
if (!formatString.Contains("{0"))
{
formatString = "{0:" + formatString + "}";
}
return String.Format(formatString, value);
}
}
protected override void OnPreviewMouseWheel(MouseWheelEventArgs e)
{
base.OnPreviewMouseWheel(e);
bool control = Keyboard.IsKeyDown(Key.LeftCtrl);
if (control)
{
double s = 1 + e.Delta * 0.0004;
var tg = new TransformGroup();
if (LayoutTransform != null)
{
tg.Children.Add(LayoutTransform);
}
tg.Children.Add(new ScaleTransform(s, s));
LayoutTransform = tg;
e.Handled = true;
}
}
private HorizontalAlignment GetHorizontalAlignment(CellRef cell)
{
int i = GetFieldIndex(cell);
if (i < ColumnDefinitions.Count)
return ColumnDefinitions[i].HorizontalAlignment;
if (ColumnAlignments != null && cell.Column < ColumnAlignments.Count)
return ColumnAlignments[cell.Column];
return DefaultHorizontalAlignment;
}
private string GetFormatString(CellRef cell, object value)
{
if (value != null)
{
var ct = GetCustomTemplate(value.GetType());
if (ct != null && ct.StringFormat != null)
return ct.StringFormat;
}
int i = GetFieldIndex(cell);
if (i < ColumnDefinitions.Count)
return ColumnDefinitions[i].StringFormat;
if (FormatStrings != null && cell.Column < FormatStrings.Count)
return FormatStrings[cell.Column];
return null;
}
private GridLength GetColumnWidth(int i)
{
if (i < ColumnDefinitions.Count)
{
if (ColumnDefinitions[i].Width.Value < 0)
return DefaultColumnWidth;
return ColumnDefinitions[i].Width;
}
if (ColumnWidths != null && i < ColumnWidths.Count)
return ColumnWidths[i];
return DefaultColumnWidth;
}
private void ColumnSplitterChangeDelta(object sender, DragDeltaEventArgs e)
{
var gs = (GridSplitter)sender;
var tt = gs.ToolTip as ToolTip;
if (tt == null)
{
tt = new ToolTip();
gs.ToolTip = tt;
tt.IsOpen = true;
}
int column = Grid.GetColumn(gs);
var width = columnGrid.ColumnDefinitions[column].ActualWidth;
tt.Content = string.Format("Width: {0}", width); // device-independent units
tt.PlacementTarget = columnGrid;
tt.Placement = PlacementMode.Relative;
var p = Mouse.GetPosition(columnGrid);
tt.HorizontalOffset = p.X;
tt.VerticalOffset = gs.ActualHeight + 4;
}
private void ColumnSplitterChangeStarted(object sender, DragStartedEventArgs dragStartedEventArgs)
{
var gs = (GridSplitter)sender;
ColumnSplitterChangeDelta(sender, null);
}
private void ColumnSplitterChangeCompleted(object sender, DragCompletedEventArgs dragCompletedEventArgs)
{
var gs = (GridSplitter)sender;
var tt = gs.ToolTip as ToolTip;
if (tt != null)
{
tt.IsOpen = false;
gs.ToolTip = null;
}
for (int i = 0; i < sheetGrid.ColumnDefinitions.Count; i++)
{
sheetGrid.ColumnDefinitions[i].Width = columnGrid.ColumnDefinitions[i].Width;
}
}
private static Type GetListItemType(IEnumerable list)
{
if (list == null)
return null;
foreach (var item in list)
{
if (item != null)
return item.GetType();
}
return null;
}
private static Type GetListItemType(Type listType)
{
// http://stackoverflow.com/questions/1043755/c-generic-list-t-how-to-get-the-type-of-t
foreach (var interfaceType in listType.GetInterfaces())
{
if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IList<>))
{
var args = interfaceType.GetGenericArguments();
if (args.Length > 0)
return args[0];
}
}
return null;
}
public bool DeleteItem(int index, bool updateGrid)
{
if (Content is Array)
{
return false;
}
var list = Content as IList;
if (list == null)
{
return false;
}
if (index < 0 || index >= list.Count)
{
return false;
}
list.RemoveAt(index);
if (updateGrid)
{
this.UpdateGridContent();
}
return true;
}
public bool InsertItem(int index, bool updateGrid = true)
{
if (Content is Array)
{
return false;
}
var list = Content as IList;
if (list == null)
{
return false;
}
var listType = list.GetType();
var itemType = GetListItemType(listType);
object newItem = null;
if (itemType == typeof(string))
{
newItem = string.Empty;
}
if (itemType == typeof(double))
{
newItem = 0.0;
}
if (itemType == typeof(int))
{
newItem = 0;
}
try
{
if (newItem == null)
{
newItem = CreateInstance(itemType);
}
}
catch
{
return false;
}
if (index < 0)
{
list.Add(newItem);
}
else
{
list.Insert(index, newItem);
}
if (updateGrid)
{
UpdateGridContent();
}
return true;
}
protected virtual object CreateInstance(Type itemType)
{
object newItem;
newItem = Activator.CreateInstance(itemType);
return newItem;
}
private void addItemCell_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
InsertItem(-1);
}
private void CellChecked(object sender, RoutedEventArgs e)
{
var chkbox = sender as CheckBox;
if (chkbox == null)
{
return;
}
int row = Grid.GetRow(chkbox);
int column = Grid.GetColumn(chkbox);
CurrentCell = new CellRef(row, column);
SelectionCell = new CellRef(row, column);
// Binding was not used here, so update the value of the cell
TrySetCellValue(CurrentCell, chkbox.IsChecked);
UpdateCellContent(CurrentCell);
}
//private object[,] ConvertItemsSourceToArray(IEnumerable items)
//{
// int nItems = items.Cast<object>().Count();
// var actualDataFields = DataFields;
// var actualColumnHeaders = ColumnHeaders;
// if (actualDataFields == null)
// {
// AutoGenerateColumns(items, out actualDataFields, out actualColumnHeaders);
// }
// ActualDataFields = actualDataFields;
// ActualColumnHeaders = actualColumnHeaders;
// int nFields = actualDataFields != null ? actualDataFields.Count : 1;
// var pi = new PropertyInfo[nFields];
// var cells = !ItemsInColumns ? new object[nItems, nFields] : new object[nFields, nItems];
// int i = 0;
// foreach (var item in items)
// {
// var type = item.GetType();
// for (int j = 0; j < nFields; j++)
// {
// object value = null;
// if (actualDataFields == null)
// {
// value = item;
// }
// else
// {
// if (pi[j] == null || pi[j].DeclaringType != type)
// {
// pi[j] = type.GetProperty(actualDataFields[j]);
// }
// if (pi[j] != null)
// {
// value = pi[j].GetValue(item, null);
// }
// else
// {
// value = item;
// }
// }
// if (!ItemsInColumns)
// {
// cells[i, j] = value;
// }
// else
// {
// cells[j, i] = value;
// }
// }
// i++;
// }
// return cells;
//}
protected virtual void AutoGenerateColumns(IEnumerable items, out StringCollection dataFields,
out StringCollection columnHeaders)
{
var itemType = GetListItemType(items.GetType());
// todo: how to find the right type?
if (itemType == null)
itemType = GetListItemType(items);
dataFields = new StringCollection();
columnHeaders = new StringCollection();
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(itemType))
{
if (!descriptor.IsBrowsable)
{
continue;
}
dataFields.Add(descriptor.Name);
var displayName = descriptor.DisplayName;
if (String.IsNullOrEmpty(displayName))
{
displayName = descriptor.Name;
}
columnHeaders.Add(displayName);
}
}
private void ColumnSplitterDoubleClick(object sender, MouseButtonEventArgs e)
{
int column = Grid.GetColumn((GridSplitter)sender);
AutoSizeColumn(column);
}
public void AutoSizeColumn(int column)
{
var h = GetColumnElement(column);
double maxwidth = h.ActualWidth;
for (int i = 0; i < sheetGrid.RowDefinitions.Count; i++)
{
var c = GetCellElement(new CellRef(i, column)) as FrameworkElement;
if (c != null)
{
maxwidth = Math.Max(maxwidth, c.ActualWidth + c.Margin.Left + c.Margin.Right);
}
}
sheetGrid.ColumnDefinitions[column].Width =
columnGrid.ColumnDefinitions[column].Width = new GridLength((int)maxwidth + 2);
}
private FrameworkElement GetColumnElement(int column)
{
return columnGrid.Children[1 + 3 * column + 1] as FrameworkElement;
}
private void ScrollViewerScrollChanged(object sender, ScrollChangedEventArgs e)
{
columnScroller.ScrollToHorizontalOffset(sheetScroller.HorizontalOffset);
rowScroller.ScrollToVerticalOffset(sheetScroller.VerticalOffset);
if (IsVirtualizing)
VirtualizeCells();
}
private void ScrollViewerSizeChanged(object sender, SizeChangedEventArgs e)
{
if (IsVirtualizing)
VirtualizeCells();
}
private void RowScrollerChanged(object sender, ScrollChangedEventArgs e)
{
sheetScroller.ScrollToVerticalOffset(e.VerticalOffset);
}
private void ColumnScrollerChanged(object sender, ScrollChangedEventArgs e)
{
sheetScroller.ScrollToHorizontalOffset(e.HorizontalOffset);
}
public void GetVisibleCells(out CellRef topLeft, out CellRef bottomRight)
{
double left = sheetScroller.HorizontalOffset;
double right = left + sheetScroller.ActualWidth;
double top = sheetScroller.VerticalOffset;
double bottom = top + sheetScroller.ActualHeight;
topLeft = GetCell(new Point(left, top));
bottomRight = GetCell(new Point(right, bottom));
}
public void ScrollIntoView(CellRef cellRef)
{
var pos0 = GetPosition(cellRef);
var pos1 = GetPosition(new CellRef(cellRef.Row + 1, cellRef.Column + 1));
double scrollBarWidth = 20;
double scrollBarHeight = 20;
if (pos0.X < sheetScroller.HorizontalOffset)
{
sheetScroller.ScrollToHorizontalOffset(pos0.X);
}
if (pos1.X > sheetScroller.HorizontalOffset + sheetScroller.ActualWidth - scrollBarWidth)
{
sheetScroller.ScrollToHorizontalOffset(Math.Max(pos1.X - sheetScroller.ActualWidth + scrollBarWidth, 0));
}
if (pos0.Y < sheetScroller.VerticalOffset)
{
sheetScroller.ScrollToVerticalOffset(pos0.Y);
}
if (pos1.Y > sheetScroller.VerticalOffset + sheetScroller.ActualHeight - scrollBarHeight)
{
sheetScroller.ScrollToVerticalOffset(Math.Max(pos1.Y - sheetScroller.ActualHeight + scrollBarHeight, 0));
}
}
protected override void OnTextInput(TextCompositionEventArgs e)
{
base.OnTextInput(e);
if (e.Text == "\r")
{
return;
}
ShowTextBoxEditor();
textEditor.Text = e.Text;
textEditor.CaretIndex = textEditor.Text.Length;
}
public void MoveCurrentCell(int deltaRows, int deltaColumns)
{
int row = CurrentCell.Row;
int column = CurrentCell.Column;
row += deltaRows;
column += deltaColumns;
if (row < 0)
{
row = Rows - 1;
column--;
}
if (row >= Rows && !CanInsertRows)
{
column++;
row = 0;
}
if (column < 0)
{
column = 0;
}
if (column >= Columns && !CanInsertColumns)
{
column = 0;
}
CurrentCell = new CellRef(row, column);
SelectionCell = new CellRef(row, column);
ScrollIntoView(CurrentCell);
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
bool control = Keyboard.IsKeyDown(Key.LeftCtrl);
bool shift = Keyboard.IsKeyDown(Key.LeftShift);
bool alt = Keyboard.IsKeyDown(Key.LeftAlt);
int row = shift ? SelectionCell.Row : CurrentCell.Row;
int column = shift ? SelectionCell.Column : CurrentCell.Column;
switch (e.Key)
{
case Key.Up:
if (row > 0)
{
row--;
}
if (endPressed)
{
FindNext(ref row, ref column, -1, 0);
}
if (control)
{
row = 0;
}
break;
case Key.Down:
if (row < Rows - 1 || CanInsertRows)
{
row++;
}
if (endPressed)
{
FindNext(ref row, ref column, 1, 0);
}
if (control)
{
row = Rows - 1;
}
break;
case Key.Enter:
MoveCurrentCell(shift ? -1 : 1, 0);
e.Handled = true;
return;
case Key.Left:
if (column > 0)
{
column--;
}
if (endPressed)
{
FindNext(ref row, ref column, 0, -1);
}
if (control)
{
column = 0;
}
break;
case Key.Right:
if (column < Columns - 1 || CanInsertColumns)
{
column++;
}
if (endPressed)
{
FindNext(ref row, ref column, 0, 1);
}
if (control)
{
column = Columns - 1;
}
break;
case Key.End:
endPressed = true;
break;
case Key.Home:
column = 0;
row = 0;
break;
case Key.Delete:
Delete();
break;
case Key.F2:
ShowTextBoxEditor();
break;
case Key.Space:
bool value = true;
var cvalue = GetCellValue(CurrentCell);
if (cvalue is bool)
{
value = (bool)cvalue;
value = !value;
}
if (SetCheckInSelectedCells(value))
{
e.Handled = true;
}
if (OpenCombo())
{
e.Handled = true;
}
return;
case Key.A:
if (control)
{
SelectAll();
e.Handled = true;
}
return;
case Key.C:
if (control && alt)
{
Clipboard.SetText(ToCsv());
e.Handled = true;
}
return;
default:
return;
}
if (e.Key != Key.End)
endPressed = false;
if (shift)
{
SelectionCell = new CellRef(row, column);
}
else
{
CurrentCell = new CellRef(row, column);
SelectionCell = new CellRef(row, column);
}
ScrollIntoView(new CellRef(row, column));
e.Handled = true;
}
private void FindNext(ref int row, ref int column, int deltaRow, int deltaColumn)
{
while (row >= 0 && row < Rows && column >= 0 && column < Columns - 1)
{
var v = GetCellValue(new CellRef(row, column));
if (v == null || String.IsNullOrEmpty(v.ToString()))
break;
row += deltaRow;
column += deltaColumn;
}
}
private bool OpenCombo()
{
if (enumEditor.Visibility == Visibility.Visible)
{
enumEditor.IsDropDownOpen = true;
enumEditor.Focus();
return true;
}
return false;
}
private void SelectAll()
{
CurrentCell = new CellRef(0, 0);
SelectionCell = new CellRef(Rows - 1, Columns - 1);
ScrollIntoView(CurrentCell);
}
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonDown(e);
var pos = e.GetPosition(sheetGrid);
var cellRef = GetCell(pos);
if (cellRef.Column == -1 || cellRef.Row == -1)
{
return;
}
if (cellRef.Row >= Rows && !CanInsertRows)
{
return;
}
if (cellRef.Column > Columns && !CanInsertColumns)
{
return;
}
if (autoFillSelection.Visibility == Visibility.Visible)
{
AutoFillCell = cellRef;
Mouse.OverrideCursor = autoFillBox.Cursor;
autoFillToolTip.IsOpen = true;
}
else
{
bool shift = Keyboard.IsKeyDown(Key.LeftShift);
if (!shift)
{
CurrentCell = cellRef;
}
SelectionCell = cellRef;
ScrollIntoView(cellRef);
Mouse.OverrideCursor = sheetGrid.Cursor;
}
CaptureMouse();
isCapturing = true;
Focus();
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (!isCapturing)
{
return;
}
var pos = e.GetPosition(sheetGrid);
var cellRef = GetCell(pos);
if (cellRef.Column == -1 || cellRef.Row == -1)
{
return;
}
if (cellRef.Row >= Rows && !CanInsertRows)
{
return;
}
if (cellRef.Column > Columns && !CanInsertColumns)
{
return;
}
if (autoFillSelection.Visibility == Visibility.Visible)
{
AutoFillCell = cellRef;
object result;
if (autoFiller.TryExtrapolate(cellRef, CurrentCell, SelectionCell, AutoFillCell, out result))
{
var fmt = GetFormatString(cellRef, result);
autoFillToolTip.Content = FormatValue(result, fmt);
}
autoFillToolTip.Placement = PlacementMode.Relative;
var p = e.GetPosition(autoFillSelection);
autoFillToolTip.HorizontalOffset = p.X + 8;
autoFillToolTip.VerticalOffset = p.Y + 8;
}
else
{
SelectionCell = cellRef;
}
ScrollIntoView(cellRef);
}
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
{
OnMouseUp(e);
isCapturing = false;
ReleaseMouseCapture();
Mouse.OverrideCursor = null;
if (autoFillSelection.Visibility == Visibility.Visible)
{
autoFiller.AutoFill(CurrentCell, SelectionCell, AutoFillCell);
autoFillSelection.Visibility = Visibility.Hidden;
autoFillToolTip.IsOpen = false;
}
}
public Point GetPosition(CellRef cellRef)
{
double x = 0;
double y = 0;
for (int j = 0; j < cellRef.Column && j < sheetGrid.ColumnDefinitions.Count; j++)
{
x += sheetGrid.ColumnDefinitions[j].ActualWidth;
}
for (int i = 0; i < cellRef.Row && i < sheetGrid.RowDefinitions.Count; i++)
{
y += sheetGrid.RowDefinitions[i].ActualHeight;
}
return new Point(x, y);
}
public CellRef GetCell(Point position)
{
double w = 0;
int column = -1;
int row = -1;
for (int j = 0; j < sheetGrid.ColumnDefinitions.Count; j++)
{
double aw = sheetGrid.ColumnDefinitions[j].ActualWidth;
if (position.X < w + aw)
{
column = j;
break;
}
w += aw;
}
if (w > 0 && column == -1)
column = sheetGrid.ColumnDefinitions.Count - 1;
double h = 0;
for (int i = 0; i < sheetGrid.RowDefinitions.Count; i++)
{
double ah = sheetGrid.RowDefinitions[i].ActualHeight;
if (position.Y < h + ah)
{
row = i;
break;
}
h += ah;
}
if (h > 0 && row == -1)
row = sheetGrid.RowDefinitions.Count - 1;
if (column == -1 || row == -1)
{
return new CellRef(-1, -1);
}
return new CellRef(row, column);
}
public virtual bool TrySetCellValue(CellRef cell, object value)
{
Array cells;
if (Content.GetType().IsArray)
{
cells = (Array)Content;
var eltype = cells.GetType().GetElementType();
object convertedValue;
if (TryConvert(value, eltype, out convertedValue))
{
try
{
if (cells.Rank > 1)
{
cells.SetValue(convertedValue, cell.Row, cell.Column);
}
else
{
cells.SetValue(convertedValue, cell.Row);
}
UpdateCellContent(cell);
return true;
}
catch
{
return false;
}
}
// wrong type
return false;
}
var items = Content as IEnumerable;
if (items != null)
{
var current = GetItem(cell);
int fieldIndex = !ItemsInColumns ? cell.Column : cell.Row;
if (current != null)
{
var field = GetDataField(cell);
var pi = current.GetType().GetProperty(field);
if (pi == null)
{
//var list = Content as IList;
//int itemIndex=GetItemIndex(cell);
//object convertedValue;
//if (TryConvert(value, pi.PropertyType, out convertedValue))
//{
// list[itemIndex]=
// todo: set the actual item to the value
return false;
}
object convertedValue;
if (TryConvert(value, pi.PropertyType, out convertedValue) && pi.CanWrite)
{
pi.SetValue(current, convertedValue, null);
if (!(current is INotifyPropertyChanged))
{
UpdateCellContent(cell);
}
return true;
}
}
}
return false;
}
private static bool TryConvert(object value, Type targetType, out object convertedValue)
{
try
{
if (value != null && targetType == value.GetType())
{
convertedValue = value;
return true;
}
if (targetType == typeof(string))
{
convertedValue = value != null ? value.ToString() : null;
return true;
}
if (targetType == typeof(double))
{
convertedValue = Convert.ToDouble(value);
return true;
}
if (targetType == typeof(int))
{
convertedValue = Convert.ToInt32(value);
return true;
}
var converter = TypeDescriptor.GetConverter(targetType);
if (converter != null && value != null && converter.CanConvertFrom(value.GetType()))
{
convertedValue = converter.ConvertFrom(value);
return true;
}
convertedValue = null;
return false;
}
catch (Exception e)
{
Trace.WriteLine(e);
convertedValue = null;
return false;
}
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/SimpleGrid/SimpleGrid.cs | C# | gpl3 | 89,125 |
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
namespace PropertyTools.Wpf
{
public class GridLengthCollectionConverter : TypeConverter
{
private static readonly char[] SplitterChars = ",;".ToCharArray();
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
var s = value as string;
if (s != null)
{
var glc = new GridLengthConverter();
var c = new Collection<GridLength>();
foreach (var item in s.Split(SplitterChars))
{
c.Add((GridLength)glc.ConvertFrom(item));
}
return c;
}
return base.ConvertFrom(context, culture, value);
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/SimpleGrid/GridLengthCollectionConverter.cs | C# | gpl3 | 1,214 |
using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
namespace PropertyTools.Wpf
{
[TypeConverter(typeof(StringCollection))]
public class StringCollectionConverter : TypeConverter
{
private static readonly char[] SplitterChars = ",;".ToCharArray();
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
var s = value as string;
if (s != null)
{
var sc = new StringCollection();
foreach (var item in s.Split(SplitterChars))
{
sc.Add(item);
}
return sc;
}
return base.ConvertFrom(context, culture, value);
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/SimpleGrid/StringCollectionConverter.cs | C# | gpl3 | 1,148 |
using System;
using System.Linq;
namespace PropertyTools.Wpf
{
/// <summary>
/// Addtion, subctraction and multiplication for all kinds of objects.
/// Uses reflection to invoke the operators.
/// </summary>
public static class ReflectionMath
{
/// <summary>
/// Performs addition with the op_Addition operator. A return value indicates whether the addition succeeded or failed.
/// </summary>
/// <param name="o1">The first object.</param>
/// <param name="o2">The second object.</param>
/// <param name="result">The sum.</param>
/// <returns>True if the addition succeeded.</returns>
public static bool TryAdd(object o1, object o2, out object result)
{
if (o1 is double && o2 is double)
{
result = (double)o1 + (double)o2;
return true;
}
if (o1 is int && o2 is int)
{
result = (int)o1 + (int)o2;
return true;
}
return TryInvoke("op_Addition", o1, o2, out result);
}
/// <summary>
/// Performs subtraction with the op_Subtraction operator. A return value indicates whether the addition succeeded or failed.
/// </summary>
/// <param name="o1">The first object.</param>
/// <param name="o2">The second object.</param>
/// <param name="result">The difference.</param>
/// <returns>True if the subtraction succeeded.</returns>
public static bool TrySubtract(object o1, object o2, out object result)
{
if (o1 is double && o2 is double)
{
result = (double)o1 - (double)o2;
return true;
}
if (o1 is int && o2 is int)
{
result = (int)o1 - (int)o2;
return true;
}
return TryInvoke("op_Subtraction", o1, o2, out result);
}
/// <summary>
/// Performs multiplication with the op_Multiplication operator. A return value indicates whether the addition succeeded or failed.
/// </summary>
/// <param name="o1">The first object.</param>
/// <param name="o2">The second object.</param>
/// <param name="result">The product.</param>
/// <returns>True if the multiplication succeeded.</returns>
public static bool TryMultiply(object o1, object o2, out object result)
{
if (o1 is double && o2 is double)
{
result = (double)o1 * (double)o2;
return true;
}
if (o1 is int && o2 is int)
{
result = (int)o1 * (int)o2;
return true;
}
// Implementation of the multiply operator for TimeSpan
if (o1 is TimeSpan && o2 is double)
{
double seconds = ((TimeSpan)o1).TotalSeconds * (double)o2;
result = TimeSpan.FromSeconds(seconds);
return true;
}
return TryInvoke("op_Multiply", o1, o2, out result);
}
private static bool TryInvoke(string methodName, object o1, object o2, out object result)
{
try
{
var t1 = o1.GetType();
var t2 = o2.GetType();
var mi =
t1.GetMethods().FirstOrDefault(m => m.Name == methodName && m.GetParameters()[1].ParameterType == t2);
if (mi == null)
{
result = null;
return false;
}
result = mi.Invoke(null, new[] { o1, o2 });
return true;
}
catch
{
result = null;
return false;
}
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/SimpleGrid/ReflectionMath.cs | C# | gpl3 | 4,035 |
using System;
using System.ComponentModel;
using System.Windows.Controls.Primitives;
namespace PropertyTools.Wpf
{
/// <summary>
/// Properties marked [Slidable] are using a slider
/// </summary>
public class SlidablePropertyViewModel : PropertyViewModel
{
public double SliderMaximum { get; set; }
public double SliderMinimum { get; set; }
public double SliderSmallChange { get; set; }
public double SliderLargeChange { get; set; }
public bool SliderSnapToTicks { get; set; }
public double SliderTickFrequency { get; set; }
public TickPlacement SliderTickPlacement { get; set; }
public double DoubleValue
{
get
{
if (Value == null)
return 0;
var t = Value.GetType();
if (t == typeof(int))
{
int i = (int)Value;
return i;
}
if (t == typeof(double))
return (double)Value;
if (t == typeof(float))
return (float)Value;
return 0;
}
set
{
Value = value;
}
}
public SlidablePropertyViewModel(object instance, PropertyDescriptor descriptor, PropertyEditor owner)
: base(instance, descriptor, owner)
{
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/PropertyEditor/PropertyViewModel/SlidablePropertyViewModel.cs | C# | gpl3 | 1,506 |
using System.ComponentModel;
using System.Windows.Input;
namespace PropertyTools.Wpf
{
/// <summary>
/// Properties that are marked [resettable(...)] have a reset button
/// </summary>
public class ResettablePropertyViewModel : PropertyViewModel
{
private readonly object instance;
private readonly PropertyDescriptor resettableDescriptor;
public ResettablePropertyViewModel(object instance, PropertyDescriptor descriptor, PropertyEditor owner)
: base(instance, descriptor, owner)
{
this.instance = instance;
resettableDescriptor = descriptor;
ResetCommand = new DelegateCommand(ExecuteReset);
var resettableAttr = AttributeHelper.GetFirstAttribute<ResettableAttribute>(resettableDescriptor);
if (resettableAttr != null)
{
Label = (string) resettableAttr.ButtonLabel;
}
}
public string ResettablePropertyName
{
get
{
if (resettableDescriptor != null)
{
return resettableDescriptor.Name;
}
return null;
}
}
public string Label { get; set; }
/// <summary>
/// Gets or sets BrowseCommand.
/// </summary>
public ICommand ResetCommand { get; set; }
public void ExecuteReset()
{
var reset = instance as IResettableProperties;
if (reset != null)
{
Value = reset.GetResetValue(resettableDescriptor.Name);
}
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/PropertyEditor/PropertyViewModel/ResettablePropertyViewModel.cs | C# | gpl3 | 1,724 |
using System;
using System.Collections;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Windows;
namespace PropertyTools.Wpf
{
/// <summary>
/// The Property ViewModel
/// </summary>
public class PropertyViewModel : ViewModelBase, IDataErrorInfo, IEditableObject
{
private bool isEnabled = true;
private bool isVisible = true;
/// <summary>
/// Initializes a new instance of the <see cref="PropertyViewModel"/> class.
/// </summary>
/// <param name="instance">The instance being edited</param>
/// <param name="descriptor">The property descriptor</param>
/// <param name="owner">The parent PropertyEditor</param>
public PropertyViewModel(object instance, PropertyDescriptor descriptor, PropertyEditor owner)
: base(owner)
{
Instance = instance;
Descriptor = descriptor;
Header = descriptor.DisplayName;
ToolTip = descriptor.Description;
Height = double.NaN;
}
/// <summary>
/// Gets or sets the format string.
/// </summary>
/// <value>The format string.</value>
public string FormatString { get; set; }
/// <summary>
/// Gets or sets the height of the editor for the property.
/// </summary>
/// <value>The height.</value>
public double Height { get; set; }
/// <summary>
/// Gets or sets the max length of text.
/// </summary>
public int MaxLength { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the property should be edited as multiline.
/// </summary>
/// <value><c>true</c> if multiline; otherwise, <c>false</c>.</value>
public bool AcceptsReturn { get; set; }
/// <summary>
/// Gets or sets the text wrapping for multiline strings.
/// </summary>
/// <value>The text wrapping mode.</value>
public TextWrapping TextWrapping { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is enumerable.
/// </summary>
/// <value>
/// <c>true</c> if this instance is enumerable; otherwise, <c>false</c>.
/// </value>
public bool IsEnumerable { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this text property should use PropertyChanged as UpdateTrigger.
/// </summary>
public bool AutoUpdateText { get; set; }
/// <summary>
/// Gets the property template selector.
/// </summary>
/// <value>The property template selector.</value>
public PropertyTemplateSelector PropertyTemplateSelector
{
get { return Owner.PropertyTemplateSelector; }
}
/// <summary>
/// Gets or sets the instance.
/// </summary>
/// <value>The instance.</value>
public object Instance { get; private set; }
/// <summary>
/// Gets or sets the property descriptor.
/// </summary>
/// <value>The descriptor.</value>
public PropertyDescriptor Descriptor { get; private set; }
/// <summary>
/// Gets or sets the descriptor for the property's IsEnabled.
/// </summary>
/// <value>The is enabled descriptor.</value>
public PropertyDescriptor IsEnabledDescriptor { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this property is enabled.
/// </summary>
/// <value>
/// <c>true</c> if this instance is enabled; otherwise, <c>false</c>.
/// </value>
public bool IsEnabled
{
get
{
if (IsEnabledDescriptor != null)
return (bool)IsEnabledDescriptor.GetValue(FirstInstance);
if (Owner.PropertyStateProvider != null)
return isEnabled && Owner.PropertyStateProvider.IsEnabled(FirstInstance, Descriptor);
return isEnabled;
}
set
{
if (IsEnabledDescriptor != null)
IsEnabledDescriptor.SetValue(FirstInstance, value);
isEnabled = value;
NotifyPropertyChanged("IsEnabled");
}
}
/// <summary>
/// Gets or sets the descriptor for the property's IsVisible.
/// </summary>
/// <value>The is Visible descriptor.</value>
public PropertyDescriptor IsVisibleDescriptor { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this property is Visible.
/// </summary>
/// <value>
/// <c>true</c> if this instance is Visible; otherwise, <c>false</c>.
/// </value>
public bool IsVisible
{
get
{
if (IsVisibleDescriptor != null)
return (bool)IsVisibleDescriptor.GetValue(FirstInstance);
if (Owner.PropertyStateProvider != null)
return isVisible && Owner.PropertyStateProvider.IsVisible(FirstInstance, Descriptor);
return isVisible;
}
set
{
if (IsVisibleDescriptor != null)
IsVisibleDescriptor.SetValue(FirstInstance, value);
isVisible = value;
NotifyPropertyChanged("IsVisible");
NotifyPropertyChanged("Visibility");
}
}
/// <summary>
/// Gets the property error.
/// </summary>
/// <value>The property error.</value>
public string PropertyError
{
get
{
return Owner.PropertyStateProvider != null
? Owner.PropertyStateProvider.GetError(FirstInstance, Descriptor)
: null;
}
}
/// <summary>
/// Gets the property warning.
/// </summary>
/// <value>The property warning.</value>
public string PropertyWarning
{
get
{
return Owner.PropertyStateProvider != null
? Owner.PropertyStateProvider.GetWarning(FirstInstance, Descriptor)
: null;
}
}
/// <summary>
/// Gets the visibility of the property.
/// </summary>
/// <value>The visibility.</value>
public Visibility Visibility
{
get { return IsVisible ? Visibility.Visible : Visibility.Collapsed; }
}
/// <summary>
/// Gets the first instance if the Instance is an Enumerable, otherwise return the Instance.
/// </summary>
/// <value>The first instance.</value>
public object FirstInstance
{
get
{
if (IsEnumerable)
{
var list = Instance as IEnumerable;
if (list == null)
{
throw new InvalidOperationException("Instance should be a list.");
}
return list.Cast<object>().FirstOrDefault();
}
return Instance;
}
}
/// <summary>
/// Gets the instances or a single Instance as an Enumerable.
/// </summary>
/// <value>The instances.</value>
public IEnumerable Instances
{
get
{
if (IsEnumerable)
{
var list = Instance as IEnumerable;
if (list == null)
{
throw new InvalidOperationException("Instance should be a list.");
}
foreach (object o in list)
yield return o;
}
else
{
yield return Instance;
}
}
}
/// <summary>
/// Gets or sets the value of the property.
/// </summary>
/// <value>The value.</value>
public object Value
{
get
{
object value;
if (IsEnumerable)
{
var list = Instance as IEnumerable;
if (list == null)
{
throw new InvalidOperationException("Instance should be an enumerable.");
}
value = GetValueFromEnumerable(list);
}
else
{
value = GetValue(Instance);
}
if (!String.IsNullOrEmpty(FormatString))
return FormatValue(value);
return value;
}
set
{
if (IsEnumerable)
{
var list = Instance as IEnumerable;
if (list == null)
{
throw new InvalidOperationException("Instance should be an enumerable.");
}
OldValue = null;
foreach (object item in list)
{
SetValue(item, value);
}
}
else
{
OldValue = Value;
SetValue(Instance, value);
}
}
}
private static TimeSpanFormatter timeSpanFormatter = new TimeSpanFormatter();
private string FormatValue(object value)
{
var f = FormatString;
if (!f.Contains("{0"))
f = string.Format("{{0:{0}}}", f);
if (value is TimeSpan) return string.Format(timeSpanFormatter, f, value);
return string.Format(f, value);
}
public object OldValue { get; set; }
#region IDataErrorInfo Members
string IDataErrorInfo.this[string columnName]
{
get
{
var dei = Instance as IDataErrorInfo;
if (dei != null)
return dei[Descriptor.Name];
return null;
}
}
string IDataErrorInfo.Error
{
get
{
var dei = Instance as IDataErrorInfo;
if (dei != null)
return dei.Error;
return null;
}
}
#endregion
/// <summary>
/// Subscribes to the ValueChanged event.
/// </summary>
public virtual void SubscribeValueChanged()
{
SubscribeValueChanged(Descriptor, InstancePropertyChanged);
if (IsEnabledDescriptor != null)
{
SubscribeValueChanged(IsEnabledDescriptor, IsEnabledChanged);
}
if (IsVisibleDescriptor != null)
{
SubscribeValueChanged(IsVisibleDescriptor, IsVisibleChanged);
}
}
private void IsEnabledChanged(object sender, EventArgs e)
{
NotifyPropertyChanged("IsEnabled");
}
private void IsVisibleChanged(object sender, EventArgs e)
{
NotifyPropertyChanged("IsVisible");
NotifyPropertyChanged("Visibility");
}
/// <summary>
/// Unsubscribes the value changed event.
/// </summary>
public virtual void UnsubscribeValueChanged()
{
UnsubscribeValueChanged(Descriptor, InstancePropertyChanged);
if (IsEnabledDescriptor != null)
{
UnsubscribeValueChanged(IsEnabledDescriptor, IsEnabledChanged);
}
if (IsVisibleDescriptor != null)
{
UnsubscribeValueChanged(IsVisibleDescriptor, IsVisibleChanged);
}
}
/// <summary>
/// Subscribes to the ValueChanged event.
/// </summary>
protected void SubscribeValueChanged(PropertyDescriptor descriptor, EventHandler handler)
{
if (IsEnumerable)
{
var list = Instance as IEnumerable;
if (list == null)
{
throw new InvalidOperationException("Instance should be a list.");
}
foreach (object item in list)
descriptor.AddValueChanged(GetPropertyOwner(descriptor, item), handler);
}
else
{
descriptor.AddValueChanged(GetPropertyOwner(descriptor, Instance), handler);
}
}
private object GetPropertyOwner(PropertyDescriptor descriptor, object instance)
{
var tdp = TypeDescriptor.GetProvider(instance);
var td = tdp.GetTypeDescriptor(instance);
var c = td.GetPropertyOwner(descriptor);
return c;
}
/// <summary>
/// Unsubscribes the value changed event.
/// </summary>
protected void UnsubscribeValueChanged(PropertyDescriptor descriptor, EventHandler handler)
{
if (IsEnumerable)
{
var list = Instance as IEnumerable;
if (list == null)
{
throw new InvalidOperationException("Instance should be a list.");
}
foreach (object item in list)
descriptor.RemoveValueChanged(GetPropertyOwner(descriptor, item), handler);
}
else
{
descriptor.RemoveValueChanged(GetPropertyOwner(descriptor, Instance), handler);
}
}
private void InstancePropertyChanged(object sender, EventArgs e)
{
// Sending notification when the instance has been changed
NotifyPropertyChanged("Value");
}
/// <summary>
/// The the current value from an IEnumerable instance
/// </summary>
/// <param name="componentList"></param>
/// <returns>If all components in the enumerable are equal, it returns the value.
/// If values are different, it returns null.</returns>
protected object GetValueFromEnumerable(IEnumerable componentList)
{
object value = null;
foreach (object component in componentList)
{
object v = GetValue(component);
if (value == null)
{
value = v;
}
if (value != null && v == null)
{
return null;
}
if (v != null && !v.Equals(value))
{
return null;
}
}
return value;
}
private bool Convert(ref object value)
{
// Check if it neccessary to convert the value
var propertyType = Descriptor.PropertyType;
if (propertyType == typeof(object) ||
value == null && propertyType.IsClass ||
value != null && propertyType.IsAssignableFrom(value.GetType()))
{
// no conversion neccessary
}
else
{
// try to convert the value
var converter = Descriptor.Converter;
if (value != null)
{
if (propertyType == typeof(TimeSpan) && value is string)
{
value = TimeSpanParser.Parse(value as string, FormatString);
return true;
}
if (converter.CanConvertFrom(value.GetType()))
{
try
{
// Change to '.' decimal separator, and use InvariantCulture when converting
if (propertyType == typeof(float) || propertyType == typeof(double))
{
if (value is string)
value = ((string)value).Replace(',', '.');
}
if (IsHexFormatString(FormatString))
{
var hex = Int32.Parse(value as string, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
value = hex.ToString(CultureInfo.InvariantCulture);
}
value = converter.ConvertFrom(null, CultureInfo.InvariantCulture, value);
}
// Catch FormatExceptions
catch (Exception)
{
return false;
}
}
else
{
if (propertyType == typeof(float) && value is double)
{
var d = (double)value;
value = (float)d;
return true;
}
if (propertyType == typeof(int) && value is double)
{
var d = (double)value;
value = (int)d;
return true;
}
return false;
}
}
}
return true;
}
private bool IsHexFormatString(string formatString)
{
bool result = false;
if( !string.IsNullOrEmpty( formatString ) ) {
result = formatString.StartsWith("X") || formatString.Contains("{0:X" );
}
return result;
}
private bool IsModified(object component, object value)
{
// Return if the value has not been modified
var currentValue = Descriptor.GetValue(component);
if (currentValue == null && value == null)
{
return false;
}
if (value != null && value.Equals(currentValue))
{
return false;
}
return true;
}
protected virtual void SetValue(object instance, object value)
{
if (!Convert(ref value))
return;
if (!IsModified(instance, value))
return;
Descriptor.SetValue(instance, value);
}
protected virtual object GetValue(object instance)
{
return Descriptor.GetValue(instance);
}
/// <summary>
/// Updates the error/warning properties.
/// </summary>
public void UpdateErrorInfo()
{
NotifyPropertyChanged("PropertyError");
NotifyPropertyChanged("PropertyWarning");
}
#region Descriptor properties
/// <summary>
/// Gets the name of the property.
/// </summary>
/// <value>The name.</value>
public string Name
{
get { return Descriptor.Name; }
}
/// <summary>
/// Gets a value indicating whether this instance is writeable.
/// </summary>
/// <value>
/// <c>true</c> if this instance is writeable; otherwise, <c>false</c>.
/// </value>
public bool IsWriteable
{
get { return !IsReadOnly; }
}
/// <summary>
/// Gets a value indicating whether this instance is read only.
/// </summary>
/// <value>
/// <c>true</c> if this instance is read only; otherwise, <c>false</c>.
/// </value>
public bool IsReadOnly
{
get { return Descriptor.IsReadOnly; }
}
/// <summary>
/// Gets the type of the property.
/// </summary>
/// <value>The type of the property.</value>
public Type PropertyType
{
get { return Descriptor.PropertyType; }
}
/// <summary>
/// Gets the name of the property.
/// </summary>
/// <value>The name of the property.</value>
public string PropertyName
{
get { return Descriptor.Name; }
}
/// <summary>
/// Gets the display name.
/// </summary>
/// <value>The display name.</value>
public string DisplayName
{
get { return Descriptor.DisplayName; }
}
/// <summary>
/// Gets the category.
/// </summary>
/// <value>The category.</value>
public string Category
{
get { return Descriptor.Category; }
}
/// <summary>
/// Gets the description.
/// </summary>
/// <value>The description.</value>
public string Description
{
get { return Descriptor.Description; }
}
#endregion
public void BeginEdit()
{
var eo = Instance as IEditableObject;
if (eo != null)
eo.BeginEdit();
}
public void EndEdit()
{
var eo = Instance as IEditableObject;
if (eo != null)
eo.EndEdit();
}
public void CancelEdit()
{
var eo = Instance as IEditableObject;
if (eo != null)
eo.CancelEdit();
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/PropertyEditor/PropertyViewModel/PropertyViewModel.cs | C# | gpl3 | 22,626 |
using System.Collections.Generic;
using System.Linq;
using System.Windows;
namespace PropertyTools.Wpf
{
/// <summary>
/// ViewModel for categories.
/// The categories can be shown as GroupBox, Expander or by the Header.
/// </summary>
public class CategoryViewModel : ViewModelBase
{
private bool isEnabled = true;
public CategoryViewModel(string categoryName, PropertyEditor owner)
: base(owner)
{
Name = Header = categoryName;
Properties = new List<PropertyViewModel>();
}
public List<PropertyViewModel> Properties { get; private set; }
public string Name { get; set; }
public bool IsEnabled
{
get { return isEnabled; }
set
{
isEnabled = value;
NotifyPropertyChanged("IsEnabled");
}
}
public Visibility Visibility
{
get { return Visibility.Visible; }
}
public void Sort()
{
Properties = Properties.OrderBy(p => p.SortOrder).ToList();
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/PropertyEditor/PropertyViewModel/CategoryViewModel.cs | C# | gpl3 | 1,183 |
using System.ComponentModel;
using System.Windows.Input;
namespace PropertyTools.Wpf
{
public class FilePathPropertyViewModel : PropertyViewModel
{
public string Filter { get; set; }
public string DefaultExtension { get; set; }
public bool UseOpenDialog { get; set; }
public ICommand BrowseCommand { get; set; }
public IFileDialogService FileDialogService { get { return Owner.FileDialogService; } }
public FilePathPropertyViewModel(object instance, PropertyDescriptor descriptor, PropertyEditor owner)
: base(instance, descriptor, owner)
{
}
}
public class DirectoryPathPropertyViewModel : PropertyViewModel
{
public ICommand BrowseCommand { get; set; }
public IFolderBrowserDialogService FolderBrowserDialogService { get { return Owner.FolderBrowserDialogService; } }
public DirectoryPathPropertyViewModel(object instance, PropertyDescriptor descriptor, PropertyEditor owner)
: base(instance, descriptor, owner)
{
}
}
public class PasswordPropertyViewModel : PropertyViewModel
{
// public char PasswordChar { get; set; }
public PasswordPropertyViewModel(object instance, PropertyDescriptor descriptor, PropertyEditor owner)
:base(instance,descriptor,owner)
{
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/PropertyEditor/PropertyViewModel/FilePathViewModel.cs | C# | gpl3 | 1,432 |
using System.ComponentModel;
namespace PropertyTools.Wpf
{
public class CheckBoxPropertyViewModel : PropertyViewModel
{
public CheckBoxPropertyViewModel(object instance, PropertyDescriptor descriptor, PropertyEditor owner)
: base(instance, descriptor, owner)
{
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/PropertyEditor/PropertyViewModel/CheckBoxPropertyViewModel.cs | C# | gpl3 | 329 |
using System.ComponentModel;
using System.Windows;
namespace PropertyTools.Wpf
{
/// <summary>
/// Properties marked [WideProperty] are using the full width of the control
/// </summary>
public class WidePropertyViewModel : PropertyViewModel
{
public Visibility HeaderVisibility { get; private set; }
public WidePropertyViewModel(object instance, PropertyDescriptor descriptor, bool showHeader, PropertyEditor owner)
: base(instance, descriptor, owner)
{
HeaderVisibility = showHeader ? Visibility.Visible : Visibility.Collapsed;
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/PropertyEditor/PropertyViewModel/WidePropertyViewModel.cs | C# | gpl3 | 635 |
using System;
using System.ComponentModel;
namespace PropertyTools.Wpf
{
/// <summary>
/// Base class for tabs, categories and properties
/// </summary>
public abstract class ViewModelBase : INotifyPropertyChanged, IComparable
{
protected PropertyEditor Owner { get; private set; }
public string Header { get; set; }
public object ToolTip { get; set; }
public int SortOrder { get; set; }
protected ViewModelBase(PropertyEditor owner)
{
Owner = owner;
SortOrder = int.MinValue;
}
public override string ToString()
{
return Header;
}
#region Notify Property Changed Members
protected void NotifyPropertyChanged(string property)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(property));
}
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region IComparable Members
public int CompareTo(object obj)
{
return SortOrder.CompareTo(((ViewModelBase)obj).SortOrder);
}
#endregion
}
}
| zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/PropertyEditor/PropertyViewModel/ViewModelBase.cs | C# | gpl3 | 1,321 |
using System;
using System.ComponentModel;
using System.Windows;
namespace PropertyEditorLibrary
{
public class DefaultPropertyViewModelFactory : IPropertyViewModelFactory
{
private readonly PropertyEditor owner;
/// <summary>
/// Initializes a new instance of the <see cref="DefaultPropertyViewModelFactory"/> class.
/// </summary>
/// <param name="owner">The owner PropertyEditor of the factory.
/// This is neccessary in order to get the PropertyTemplateSelector to work.</param>
public DefaultPropertyViewModelFactory(PropertyEditor owner)
{
this.owner = owner;
}
public virtual PropertyViewModel CreateViewModel(object instance, PropertyDescriptor descriptor)
{
PropertyViewModel propertyViewModel = null;
// Optional by Nullable type
var nullable = descriptor.PropertyType.IsGenericType &&
descriptor.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>);
if (nullable)
propertyViewModel = new OptionalPropertyViewModel(instance, descriptor, null, owner);
// Optional by Attribute
var oa = AttributeHelper.GetAttribute<OptionalAttribute>(descriptor);
if (oa != null)
propertyViewModel = new OptionalPropertyViewModel(instance, descriptor, oa.PropertyName, owner);
// Wide
var wa = AttributeHelper.GetAttribute<WidePropertyAttribute>(descriptor);
if (wa != null)
propertyViewModel = new WidePropertyViewModel(instance, descriptor, wa.ShowHeader, owner);
// If bool properties should be shown as checkbox only (no header label), we create
// a CheckBoxPropertyViewModel
if (descriptor.PropertyType == typeof(bool) && owner != null && !owner.ShowBoolHeader)
propertyViewModel = new CheckBoxPropertyViewModel(instance, descriptor, owner);
// Properties with the Slidable attribute set
var sa = AttributeHelper.GetAttribute<SlidableAttribute>(descriptor);
if (sa != null)
propertyViewModel = new SlidablePropertyViewModel(instance, descriptor, owner)
{
SliderMinimum = sa.Minimum,
SliderMaximum = sa.Maximum,
SliderLargeChange = sa.LargeChange,
SliderSmallChange = sa.SmallChange
};
// FilePath
var fpa = AttributeHelper.GetAttribute<FilePathAttribute>(descriptor);
if (fpa != null)
propertyViewModel = new FilePathPropertyViewModel(instance, descriptor, owner) { Filter = fpa.Filter, DefaultExtension = fpa.DefaultExtension };
// DirectoryPath
var dpa = AttributeHelper.GetAttribute<DirectoryPathAttribute>(descriptor);
if (dpa != null)
propertyViewModel = new DirectoryPathPropertyViewModel(instance, descriptor, owner);
// Default text property
if (propertyViewModel == null)
{
var tp = new PropertyViewModel(instance, descriptor, owner);
propertyViewModel = tp;
}
var fsa = AttributeHelper.GetAttribute<FormatStringAttribute>(descriptor);
if (fsa != null)
propertyViewModel.FormatString = fsa.FormatString;
var ha = AttributeHelper.GetAttribute<HeightAttribute>(descriptor);
if (ha != null)
propertyViewModel.Height = ha.Height;
if (propertyViewModel.Height>0)
{
propertyViewModel.AcceptsReturn = true;
propertyViewModel.TextWrapping = TextWrapping.Wrap;
}
var soa = AttributeHelper.GetAttribute<SortOrderAttribute>(descriptor);
if (soa != null)
propertyViewModel.SortOrder = soa.SortOrder;
return propertyViewModel;
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/PropertyEditor/PropertyViewModel/DefaultPropertyViewModelFactory.cs | C# | gpl3 | 4,313 |
using System;
using System.ComponentModel;
namespace PropertyTools.Wpf
{
/// <summary>
/// Properties that are nullable or marked [Optional(...)] are enabled/disabled by a checkbox
/// </summary>
public class OptionalPropertyViewModel : PropertyViewModel
{
private bool enabledButHasNoValue;
private object previousValue;
private PropertyDescriptor optionalDescriptor;
public OptionalPropertyViewModel(object instance, PropertyDescriptor descriptor, string optionalPropertyName,
PropertyEditor owner)
: this(instance,descriptor, GetDescriptor(instance,optionalPropertyName),owner)
{
}
public string OptionalPropertyName
{
get
{
if (optionalDescriptor != null)
return optionalDescriptor.Name;
return null;
}
}
private static PropertyDescriptor GetDescriptor(object instance, string propertyName)
{
if (instance == null || propertyName == null)
return null;
return TypeDescriptor.GetProperties(instance).Find(propertyName, false);
}
public OptionalPropertyViewModel(object instance, PropertyDescriptor descriptor, PropertyDescriptor optionalDescriptor,
PropertyEditor owner)
: base(instance, descriptor, owner)
{
this.optionalDescriptor = optionalDescriptor;
// http://msdn.microsoft.com/en-us/library/ms366789.aspx
IsPropertyNullable = descriptor.PropertyType.IsGenericType &&
descriptor.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>);
IsPropertyNullable = true;
}
public bool IsPropertyNullable { get; private set; }
public bool IsOptionalChecked
{
get
{
if (optionalDescriptor != null)
return (bool)optionalDescriptor.GetValue(FirstInstance);
if (IsPropertyNullable)
{
return enabledButHasNoValue || Value != null;
}
return true; // default value is true (enable editor)
}
set
{
if (optionalDescriptor != null)
{
optionalDescriptor.SetValue(FirstInstance, value);
NotifyPropertyChanged("IsOptionalChecked");
return;
}
if (IsPropertyNullable)
{
if (value)
{
Value = previousValue;
enabledButHasNoValue = true;
}
else
{
previousValue = Value;
Value = null;
enabledButHasNoValue = false;
}
NotifyPropertyChanged("IsOptionalChecked");
return;
}
}
}
public override void SubscribeValueChanged()
{
base.SubscribeValueChanged();
if (optionalDescriptor != null)
{
SubscribeValueChanged(optionalDescriptor, IsOptionalChanged);
}
}
private void IsOptionalChanged(object sender, EventArgs e)
{
NotifyPropertyChanged("IsOptionalChecked");
}
public override void UnsubscribeValueChanged()
{
base.UnsubscribeValueChanged();
if (optionalDescriptor != null)
{
UnsubscribeValueChanged(optionalDescriptor, IsOptionalChanged);
}
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/PropertyEditor/PropertyViewModel/OptionalPropertyViewModel.cs | C# | gpl3 | 3,992 |
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Media;
namespace PropertyTools.Wpf
{
/// <summary>
/// ViewModel for the tabs.
/// </summary>
public class TabViewModel : ViewModelBase
{
public TabViewModel(string tabName, PropertyEditor owner)
: base(owner)
{
Name = Header = tabName;
Categories = new List<CategoryViewModel>();
}
public CategoryTemplateSelector CategoryTemplateSelector
{
get { return Owner.CategoryTemplateSelector; }
}
public List<CategoryViewModel> Categories { get; private set; }
public string Name { get; set; }
public ImageSource Icon { get; set; }
public Visibility IconVisibility
{
get { return Icon != null ? Visibility.Visible : Visibility.Collapsed; }
}
public bool HasErrors
{
get
{
foreach (CategoryViewModel cat in Categories)
foreach (PropertyViewModel prop in cat.Properties)
if (prop.PropertyError != null)
return true;
return false;
}
}
public bool HasWarnings
{
get
{
foreach (CategoryViewModel cat in Categories)
foreach (PropertyViewModel prop in cat.Properties)
if (prop.PropertyWarning != null)
return true;
return false;
}
}
public void Sort()
{
Categories = Categories.OrderBy(c => c.SortOrder).ToList();
}
public void UpdateErrorInfo()
{
NotifyPropertyChanged("HasErrors");
NotifyPropertyChanged("HasWarnings");
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/PropertyEditor/PropertyViewModel/TabViewModel.cs | C# | gpl3 | 1,983 |
using System;
using System.Windows;
using System.Windows.Controls;
namespace PropertyTools.Wpf
{
/// <summary>
/// The CategoryTemplateSelector is used to select a DataTemplate for the categories
/// </summary>
public class CategoryTemplateSelector : DataTemplateSelector
{
public FrameworkElement TemplateOwner { get; set; }
public PropertyEditor Owner { get; private set; }
public CategoryTemplateSelector(PropertyEditor owner)
{
Owner = owner;
}
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
var category = item as CategoryViewModel;
if (category == null)
{
throw new ArgumentException("item must be of type CategoryViewModel");
}
var key = "CategoryGroupBoxTemplate";
if (Owner.ShowCategoriesAs == ShowCategoriesAs.Expander) key = "CategoryExpanderTemplate";
if (Owner.ShowCategoriesAs == ShowCategoriesAs.Header) key = "CategoryHeaderTemplate";
var template = TryToFindDataTemplate(TemplateOwner, key);
return template;
}
private static DataTemplate TryToFindDataTemplate(FrameworkElement element, object dataTemplateKey)
{
object dataTemplate = element.TryFindResource(dataTemplateKey);
if (dataTemplate == null)
{
dataTemplateKey = new ComponentResourceKey(typeof(PropertyEditor), dataTemplateKey);
dataTemplate = element.TryFindResource(dataTemplateKey);
}
return dataTemplate as DataTemplate;
}
}
}
| zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/PropertyEditor/CategoryTemplateSelector.cs | C# | gpl3 | 1,759 |
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Collections.ObjectModel;
namespace PropertyTools.Wpf
{
/// <summary>
/// The PropertyTemplateSelector is used to select a DataTemplate given an PropertyViewModel instance.
/// The DataTemplates should be defined in the BasicEditors.xaml/ExtendedEditors.xaml
/// or in the Editors collection of the PropertyEditor.
/// This Selector can also be overriden if you want to provide custom selecting implementation.
/// </summary>
public class PropertyTemplateSelector : DataTemplateSelector
{
public Collection<TypeEditor> Editors { get; set; }
public FrameworkElement TemplateOwner { get; set; }
public PropertyEditor Owner { get; private set; }
public PropertyTemplateSelector(PropertyEditor owner)
{
Editors = new Collection<TypeEditor>();
Owner = owner;
}
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
var property = item as PropertyViewModel;
if (property == null)
{
throw new ArgumentException("item must be of type Property");
}
// Debug.WriteLine("Select template for " + property.PropertyName);
// Check if an editor is defined for the given type
foreach (var editor in Editors)
{
// checking generic type
if (property.PropertyType.IsGenericType && editor.EditedType == property.PropertyType.GetGenericTypeDefinition())
return editor.EditorTemplate;
// checking generic interfaces
foreach (var @interface in property.PropertyType.GetInterfaces())
{
if (@interface.IsGenericType)
{
if (editor.EditedType==@interface.GetGenericTypeDefinition())
return editor.EditorTemplate;
}
if (editor.EditedType==@interface)
return editor.EditorTemplate;
}
if (editor.EditedType.IsAssignableFrom(property.PropertyType))
return editor.EditorTemplate;
}
var element = container as FrameworkElement;
if (element == null)
{
return base.SelectTemplate(property.Value, container);
}
var template = FindDataTemplate(property, TemplateOwner);
// Debug.WriteLine(" Returning " + template);
return template;
}
private DataTemplate FindDataTemplate(PropertyViewModel propertyViewModel, FrameworkElement element)
{
Type propertyType = propertyViewModel.PropertyType;
if (Nullable.GetUnderlyingType(propertyType) != null)
{
propertyType = Nullable.GetUnderlyingType(propertyType);
}
// Try to find a template for the given type
var template = TryToFindDataTemplate(element, propertyType);
if (template != null)
return template;
// DataTemplates for enum types
if (propertyType.BaseType == typeof(Enum))
{
var rba = propertyViewModel.Descriptor.Attributes[typeof(RadioButtonsAttribute)] as RadioButtonsAttribute;
int nValues = Enum.GetValues( propertyType ).FilterOnBrowsableAttribute().Count;
if (rba != null)
{
if (rba.UseRadioButtons)
nValues = Owner.EnumAsRadioButtonsLimit;
else
nValues = Owner.EnumAsRadioButtonsLimit + 1;
}
if (nValues>Owner.EnumAsRadioButtonsLimit)
template = TryToFindDataTemplate(element, "ComboBoxEnumTemplate");
else
template = TryToFindDataTemplate(element, "RadioButtonsEnumTemplate");
if (template != null)
return template;
}
// Try to find a template for the base type
while (propertyType.BaseType != null)
{
propertyType = propertyType.BaseType;
template = TryToFindDataTemplate(element, propertyType);
if (template != null)
return template;
}
// If the Slidable attribute is set, use the 'sliderBox' template
if (propertyViewModel is SlidablePropertyViewModel)
{
template = TryToFindDataTemplate(element, "SliderBoxTemplate");
if (template != null)
return template;
}
if (propertyViewModel is FilePathPropertyViewModel)
{
template = TryToFindDataTemplate(element, "FilePathTemplate");
if (template != null)
return template;
}
if (propertyViewModel is DirectoryPathPropertyViewModel)
{
template = TryToFindDataTemplate(element, "DirectoryPathTemplate");
if (template != null)
return template;
}
if (propertyViewModel is PasswordPropertyViewModel)
{
template = TryToFindDataTemplate(element, "PasswordTemplate");
if (template != null)
return template;
}
// Use the default template (TextBox)
if (propertyViewModel.AutoUpdateText)
template = TryToFindDataTemplate(element, "DefaultTemplateAutoUpdate");
else
template = TryToFindDataTemplate(element, "DefaultTemplate");
return template;
}
private static DataTemplate TryToFindDataTemplate(FrameworkElement element, string key)
{
var resource = element.TryFindResource(key);
return resource as DataTemplate;
}
private static DataTemplate TryToFindDataTemplate(FrameworkElement element, Type type)
{
var key = new ComponentResourceKey(typeof(PropertyEditor), type);
// todo: this command throws an exception
return element.TryFindResource(key) as DataTemplate;
}
}
}
| zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/PropertyEditor/PropertyTemplateSelector.cs | C# | gpl3 | 6,660 |
using System.Collections.Generic;
namespace PropertyEditorLibrary
{
public class PropertyCategory : PropertyBase
{
public List<PropertyBase> Properties { get; private set; }
public PropertyCategory(string categoryName, PropertyEditor owner)
: base(owner)
{
Name = Header = categoryName;
Properties = new List<PropertyBase>();
}
}
}
| zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/PropertyEditor/PropertyModel/PropertyCategory.cs | C# | gpl3 | 435 |
using System.ComponentModel;
namespace PropertyEditorLibrary
{
/// <summary>
/// Properties marked [Slidable] are using a slider
/// </summary>
public class SlidableProperty : Property
{
public double SliderMaximum { get; set; }
public double SliderMinimum { get; set; }
public double SliderSmallChange { get; set; }
public double SliderLargeChange { get; set; }
public SlidableProperty(object instance, PropertyDescriptor descriptor, PropertyEditor owner)
: base(instance, descriptor, owner)
{
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/PropertyEditor/PropertyModel/SlidableProperty.cs | C# | gpl3 | 613 |
using System.ComponentModel;
using System.Windows;
using System;
namespace PropertyEditorLibrary
{
/// <summary>
/// Base class for tabs, categories and properties
/// </summary>
public abstract class PropertyBase : INotifyPropertyChanged, IDisposable, IComparable
{
protected PropertyEditor Owner { get; private set; }
public string Name { get; set; }
public string Header { get; set; }
public object ToolTip { get; set; }
public int SortOrder { get; set; }
#region Enabled/Visible
private bool isEnabled;
public bool IsEnabled
{
get { return isEnabled; }
set { isEnabled = value; NotifyPropertyChanged("IsEnabled"); }
}
private Visibility isVisible;
public Visibility IsVisible
{
get { return isVisible; }
set { isVisible = value; NotifyPropertyChanged("IsVisible"); }
}
#endregion
protected PropertyBase(PropertyEditor owner)
{
Owner = owner;
isEnabled = true;
isVisible = Visibility.Visible;
}
public override string ToString()
{
return Header;
}
#region Notify Property Changed Members
protected void NotifyPropertyChanged(string property)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(property));
}
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
// http://msdn.microsoft.com/en-us/library/ms244737(VS.80).aspx
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Leave out the finalizer altogether if this class doesn't
// own unmanaged resources itself, but leave the other methods
// exactly as they are.
~PropertyBase()
{
Dispose(false);
}
/// <summary>
/// The bulk of the clean-up code is implemented in Dispose(bool)
/// </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// free managed resources
}
// free native resources if there are any.
}
#region IComparable Members
public int CompareTo(object obj)
{
return SortOrder.CompareTo(((PropertyBase)obj).SortOrder);
}
#endregion
}
}
| zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/PropertyEditor/PropertyModel/PropertyBase.cs | C# | gpl3 | 2,783 |
using System.ComponentModel;
namespace PropertyEditorLibrary
{
/// <summary>
/// Properties marked [Optional(...)] are enabled/disabled by a checkbox
/// </summary>
public class OptionalProperty : Property
{
public OptionalProperty(object instance, PropertyDescriptor descriptor, string optionalPropertyName, PropertyEditor owner)
: base(instance, descriptor, owner)
{
OptionalPropertyName = optionalPropertyName;
}
#region Optional
private string optionalPropertyName;
public string OptionalPropertyName
{
get
{
return optionalPropertyName;
}
set
{
if (optionalPropertyName != value)
{
optionalPropertyName = value;
NotifyPropertyChanged("OptionalPropertyName");
}
}
}
public bool IsOptionalChecked
{
get
{
if (!string.IsNullOrEmpty(OptionalPropertyName))
return (bool)PropertyHelper.GetProperty(Instance, OptionalPropertyName);
return true; // default must be true (enable editor)
}
set
{
if (!string.IsNullOrEmpty(OptionalPropertyName))
{
PropertyHelper.SetProperty(Instance, OptionalPropertyName, value);
NotifyPropertyChanged("IsOptionalChecked");
}
}
}
#endregion
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/PropertyEditor/PropertyModel/OptionalProperty.cs | C# | gpl3 | 1,668 |
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;
namespace PropertyEditorLibrary
{
public class PropertyTab : PropertyBase
{
public CategoryTemplateSelector CategoryTemplateSelector { get { return Owner.CategoryTemplateSelector; } }
public List<PropertyCategory> Categories { get; private set; }
public ImageSource Icon { get; set; }
public Visibility IconVisibility { get { return Icon != null ? Visibility.Visible : Visibility.Collapsed; } }
public PropertyTab(string tabName, PropertyEditor owner)
: base(owner)
{
Name = Header = tabName;
Categories = new List<PropertyCategory>();
}
}
}
| zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/PropertyEditor/PropertyModel/PropertyTab.cs | C# | gpl3 | 762 |
using System.ComponentModel;
using System.Windows;
namespace PropertyEditorLibrary
{
/// <summary>
/// Properties marked [WideProperty] are using the full width of the control
/// </summary>
public class WideProperty : Property
{
public Visibility HeaderVisibility { get; private set; }
public WideProperty(object instance, PropertyDescriptor descriptor, bool noHeader, PropertyEditor owner)
: base(instance, descriptor, owner)
{
HeaderVisibility = noHeader ? Visibility.Collapsed : Visibility.Visible;
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/PropertyEditor/PropertyModel/WideProperty.cs | C# | gpl3 | 608 |
using System;
using System.ComponentModel;
using System.Collections;
namespace PropertyEditorLibrary
{
/// <summary>
/// The Property model
/// </summary>
public class Property : PropertyBase
{
public PropertyTemplateSelector PropertyTemplateSelector { get { return Owner.PropertyTemplateSelector; } }
public object Instance { get; private set; }
public PropertyDescriptor Descriptor { get; private set; }
public string FormatString { get; set; }
public double Height { get; set; }
public bool AcceptsReturn { get; set; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="instance"></param>
/// <param name="descriptor"></param>
/// <param name="owner"></param>
public Property(object instance, PropertyDescriptor descriptor, PropertyEditor owner)
: base(owner)
{
Instance = instance;
Descriptor = descriptor;
Name = descriptor.Name;
Header = descriptor.DisplayName;
ToolTip = descriptor.Description;
// todo: is this ok? could it be a weak event?
Descriptor.AddValueChanged(Instance, InstancePropertyChanged);
}
#region Descriptor properties
public bool IsWriteable
{
get { return !IsReadOnly; }
}
public bool IsReadOnly
{
get { return Descriptor.IsReadOnly; }
}
public Type PropertyType
{
get { return Descriptor.PropertyType; }
}
public string PropertyName
{
get { return Descriptor.Name; }
}
public string DisplayName
{
get { return Descriptor.DisplayName; }
}
public string Category
{
get { return Descriptor.Category; }
}
public string Description
{
get { return Descriptor.Description; }
}
#endregion
#region Event Handlers
void InstancePropertyChanged(object sender, EventArgs e)
{
// Sending notification when the instance has been changed
NotifyPropertyChanged("Value");
}
#endregion
#region IDisposable Members
protected override void Dispose(bool disposing)
{
if (disposing)
{
Descriptor.RemoveValueChanged(Instance, InstancePropertyChanged);
}
base.Dispose(disposing);
}
#endregion
#region Set/Get
/// <value>
/// Initializes the reflected Instance property
/// </value>
/// <exception cref="NotSupportedException">
/// The conversion cannot be performed
/// </exception>
public object Value
{
get
{
return OnGetProperty();
}
set
{
OnSetProperty(value);
}
}
protected virtual object OnGetProperty()
{
object value;
if (Instance is IEnumerable)
value = GetValueFromEnumerable(Instance as IEnumerable);
else
value = Descriptor.GetValue(Instance);
return value;
}
protected virtual void OnSetProperty(object value)
{
// Return if the value has not been modified
object currentValue = Descriptor.GetValue(Instance);
if (currentValue == null && value == null)
{
return;
}
if (value != null && value.Equals(currentValue))
{
return;
}
// Check if it neccessary to convert the value
Type propertyType = Descriptor.PropertyType;
if (propertyType == typeof(object) ||
value == null && propertyType.IsClass ||
value != null && propertyType.IsAssignableFrom(value.GetType()))
{
// no conversion neccessary
}
else
{
// convert the value
var converter = TypeDescriptor.GetConverter(Descriptor.PropertyType);
value = converter.ConvertFrom(value);
}
var list = Instance as IEnumerable;
if (list != null)
{
foreach (object item in list)
{
OnSetProperty(item, Descriptor, value);
}
}
else
{
OnSetProperty(Instance, Descriptor, value);
}
}
protected void OnSetProperty(object instance, PropertyDescriptor descriptor, object value)
{
// Use the PropertySetter service, if available
if (Owner.PropertySetter != null)
{
Owner.PropertySetter.SetProperty(instance, descriptor, value);
return;
}
Descriptor.SetValue(Instance, value);
}
/// <summary>
/// The the current value from an IEnumerable instance
/// </summary>
/// <param name="componentList"></param>
/// <returns></returns>
protected object GetValueFromEnumerable(IEnumerable componentList)
{
object value = null;
foreach (object component in componentList)
{
object v = Descriptor.GetValue(component);
if (value == null)
value = v;
if (value != null && !v.Equals(value))
return null;
}
return null; // no value
}
#endregion
}
}
| zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/PropertyEditor/PropertyModel/Property.cs | C# | gpl3 | 6,048 |
using System;
using System.Windows;
namespace PropertyTools.Wpf
{
/// <summary>
/// Define a datatemplate for a given type
/// </summary>
public class TypeEditor
{
public Type EditedType { get; set; }
public DataTemplate EditorTemplate { get; set; }
public bool AllowExpand { get; set; }
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/PropertyEditor/TypeEditor.cs | C# | gpl3 | 354 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace PropertyTools.Wpf
{
/// <summary>
/// The show categories as.
/// </summary>
public enum ShowCategoriesAs
{
/// <summary>
/// The group box.
/// </summary>
GroupBox,
/// <summary>
/// The expander.
/// </summary>
Expander,
/// <summary>
/// The header.
/// </summary>
Header
}
/// <summary>
/// PropertyEditor control.
/// Set the SelectedObject to define the contents of the control.
/// </summary>
public class PropertyEditor : Control
{
/// <summary>
/// The categor y_ appearance.
/// </summary>
private const string CATEGORY_APPEARANCE = "Appearance";
/// <summary>
/// The par t_ grid.
/// </summary>
private const string PART_GRID = "PART_Grid";
/// <summary>
/// The par t_ page.
/// </summary>
private const string PART_PAGE = "PART_Page";
/// <summary>
/// The par t_ tabs.
/// </summary>
private const string PART_TABS = "PART_Tabs";
/// <summary>
/// The property template selector property.
/// </summary>
public static readonly DependencyProperty PropertyTemplateSelectorProperty =
DependencyProperty.Register("PropertyTemplateSelector", typeof(PropertyTemplateSelector),
typeof(PropertyEditor), new UIPropertyMetadata(null));
/// <summary>
/// The category template selector property.
/// </summary>
public static readonly DependencyProperty CategoryTemplateSelectorProperty =
DependencyProperty.Register("CategoryTemplateSelector", typeof(CategoryTemplateSelector),
typeof(PropertyEditor), new UIPropertyMetadata(null));
/// <summary>
/// The label width property.
/// </summary>
public static readonly DependencyProperty LabelWidthProperty =
DependencyProperty.Register("LabelWidth", typeof(double), typeof(PropertyEditor),
new UIPropertyMetadata(100.0));
/// <summary>
/// The show read only properties property.
/// </summary>
public static readonly DependencyProperty ShowReadOnlyPropertiesProperty =
DependencyProperty.Register("ShowReadOnlyProperties", typeof(bool), typeof(PropertyEditor),
new UIPropertyMetadata(true, AppearanceChanged));
/// <summary>
/// The show tabs property.
/// </summary>
public static readonly DependencyProperty ShowTabsProperty =
DependencyProperty.Register("ShowTabs", typeof(bool), typeof(PropertyEditor),
new UIPropertyMetadata(true, AppearanceChanged));
/// <summary>
/// The declared only property.
/// </summary>
public static readonly DependencyProperty DeclaredOnlyProperty =
DependencyProperty.Register("DeclaredOnly", typeof(bool), typeof(PropertyEditor),
new UIPropertyMetadata(false, AppearanceChanged));
/// <summary>
/// The selected object property.
/// </summary>
public static readonly DependencyProperty SelectedObjectProperty =
DependencyProperty.Register("SelectedObject", typeof(object), typeof(PropertyEditor),
new UIPropertyMetadata(null, SelectedObjectChanged));
/// <summary>
/// The selected objects property.
/// </summary>
public static readonly DependencyProperty SelectedObjectsProperty =
DependencyProperty.Register("SelectedObjects", typeof(IEnumerable), typeof(PropertyEditor),
new UIPropertyMetadata(null, SelectedObjectsChanged));
/// <summary>
/// The show bool header property.
/// </summary>
public static readonly DependencyProperty ShowBoolHeaderProperty =
DependencyProperty.Register("ShowBoolHeader", typeof(bool), typeof(PropertyEditor),
new UIPropertyMetadata(true, AppearanceChanged));
public static readonly DependencyProperty EnumAsRadioButtonsLimitProperty =
DependencyProperty.Register("EnumAsRadioButtonsLimit", typeof(int), typeof(PropertyEditor),
new UIPropertyMetadata(4, AppearanceChanged));
/// <summary>
/// Gets or sets a value indicating whether to use the default category for uncategorized properties.
/// When this flag is false, the last defined category will be used.
/// The default value is false.
/// </summary>
public bool UseDefaultCategoryNameForUncategorizedProperties
{
get { return (bool)GetValue(UseDefaultCategoryNameForUncategorizedPropertiesProperty); }
set { SetValue(UseDefaultCategoryNameForUncategorizedPropertiesProperty, value); }
}
public static readonly DependencyProperty UseDefaultCategoryNameForUncategorizedPropertiesProperty =
DependencyProperty.Register("UseDefaultCategoryNameForUncategorizedProperties", typeof(bool), typeof(PropertyEditor), new UIPropertyMetadata(false));
/// <summary>
/// The show categories as property.
/// </summary>
public static readonly DependencyProperty ShowCategoriesAsProperty =
DependencyProperty.Register("ShowCategoriesAs", typeof(ShowCategoriesAs), typeof(PropertyEditor),
new UIPropertyMetadata(ShowCategoriesAs.GroupBox, AppearanceChanged));
/// <summary>
/// The default category name property.
/// </summary>
public static readonly DependencyProperty DefaultCategoryNameProperty =
DependencyProperty.Register("DefaultCategoryName", typeof(string), typeof(PropertyEditor),
new UIPropertyMetadata("Properties", AppearanceChanged));
/// <summary>
/// The label alignment property.
/// </summary>
public static readonly DependencyProperty LabelAlignmentProperty =
DependencyProperty.Register("LabelAlignment", typeof(HorizontalAlignment), typeof(PropertyEditor),
new UIPropertyMetadata(HorizontalAlignment.Left, AppearanceChanged));
/// <summary>
/// The localization service property.
/// </summary>
public static readonly DependencyProperty LocalizationServiceProperty =
DependencyProperty.Register("LocalizationService", typeof(ILocalizationService), typeof(PropertyEditor),
new UIPropertyMetadata(null));
/// <summary>
/// The image provider property.
/// </summary>
public static readonly DependencyProperty ImageProviderProperty =
DependencyProperty.Register("ImageProvider", typeof(IImageProvider), typeof(PropertyEditor),
new UIPropertyMetadata(null));
/// <summary>
/// The required attribute property.
/// </summary>
public static readonly DependencyProperty RequiredAttributeProperty =
DependencyProperty.Register("RequiredAttribute", typeof(Type), typeof(PropertyEditor),
new UIPropertyMetadata(null));
/// <summary>
/// The property value changed event.
/// </summary>
private static readonly RoutedEvent PropertyValueChangedEvent = EventManager.RegisterRoutedEvent(
"PropertyValueChanged",
RoutingStrategy.Bubble,
typeof(EventHandler<PropertyValueChangedEventArgs>),
typeof(PropertyEditor));
/// <summary>
/// The default tab name property.
/// </summary>
public static readonly DependencyProperty DefaultTabNameProperty =
DependencyProperty.Register("DefaultTabName", typeof(string), typeof(PropertyEditor),
new UIPropertyMetadata(null, AppearanceChanged));
/// <summary>
/// The error template property.
/// </summary>
public static readonly DependencyProperty ErrorTemplateProperty =
DependencyProperty.Register("ErrorTemplate", typeof(DataTemplate), typeof(PropertyEditor),
new UIPropertyMetadata(null));
/// <summary>
/// The warning template property.
/// </summary>
public static readonly DependencyProperty WarningTemplateProperty =
DependencyProperty.Register("WarningTemplate", typeof(DataTemplate), typeof(PropertyEditor),
new UIPropertyMetadata(null));
/// <summary>
/// The error border thickness property.
/// </summary>
public static readonly DependencyProperty ErrorBorderThicknessProperty =
DependencyProperty.Register("ErrorBorderThickness", typeof(Thickness), typeof(PropertyEditor),
new UIPropertyMetadata(new Thickness(4, 1, 4, 1)));
/// <summary>
/// The property state provider property.
/// </summary>
public static readonly DependencyProperty PropertyStateProviderProperty =
DependencyProperty.Register("PropertyStateProvider", typeof(IPropertyStateProvider),
typeof(PropertyEditor), new UIPropertyMetadata(null));
/// <summary>
/// The PropertyMap dictionary contains a map of all Properties of the current object being edited.
/// </summary>
private readonly Dictionary<string, PropertyViewModel> propertyMap;
/// <summary>
/// The content control.
/// </summary>
private ContentControl contentControl;
/// <summary>
/// The grid.
/// </summary>
private Grid grid;
/// <summary>
/// The model.
/// </summary>
private IList<TabViewModel> model;
/// <summary>
/// The property view model factory.
/// </summary>
private IPropertyViewModelFactory propertyViewModelFactory;
/// <summary>
/// The tab control.
/// </summary>
private TabControl tabControl;
/// <summary>
/// Initializes static members of the <see cref = "PropertyEditor" /> class.
/// </summary>
static PropertyEditor()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(PropertyEditor),
new FrameworkPropertyMetadata(typeof(PropertyEditor)));
}
/// <summary>
/// Initializes a new instance of the <see cref = "PropertyEditor" /> class.
/// </summary>
public PropertyEditor()
{
propertyMap = new Dictionary<string, PropertyViewModel>();
PropertyTemplateSelector = new PropertyTemplateSelector(this);
CategoryTemplateSelector = new CategoryTemplateSelector(this);
}
/// <summary>
/// Gets or sets the maximum number of enum values that can be shown using radio buttons.
/// If the value is 0, Enums will always be shown as ComboBoxes.
/// If the value is infinity, Enums will always be shown as Radiobuttons.
/// </summary>
/// <value>The limit.</value>
[Category(CATEGORY_APPEARANCE)]
public int EnumAsRadioButtonsLimit
{
get { return (int)GetValue(EnumAsRadioButtonsLimitProperty); }
set { SetValue(EnumAsRadioButtonsLimitProperty, value); }
}
/// <summary>
/// Gets or sets PropertyStateProvider.
/// </summary>
public IPropertyStateProvider PropertyStateProvider
{
get { return (IPropertyStateProvider)GetValue(PropertyStateProviderProperty); }
set { SetValue(PropertyStateProviderProperty, value); }
}
/// <summary>
/// Gets or sets ErrorBorderThickness.
/// </summary>
public Thickness ErrorBorderThickness
{
get { return (Thickness)GetValue(ErrorBorderThicknessProperty); }
set { SetValue(ErrorBorderThicknessProperty, value); }
}
/// <summary>
/// Gets or sets SelectedObjects.
/// </summary>
public IEnumerable SelectedObjects
{
get { return (IEnumerable)GetValue(SelectedObjectsProperty); }
set { SetValue(SelectedObjectsProperty, value); }
}
/// <summary>
/// Gets or sets the property view model factory.
/// This factory is used to generate the view model based on the property descriptors.
/// You can override this factory to create the view model based on your own attributes.
/// </summary>
/// <value>The property view model factory.</value>
[Browsable(false)]
public IPropertyViewModelFactory PropertyViewModelFactory
{
get
{
if (propertyViewModelFactory == null)
{
propertyViewModelFactory = new DefaultPropertyViewModelFactory(this);
}
return propertyViewModelFactory;
}
set { propertyViewModelFactory = value; }
}
/// <summary>
/// Collection of custom editors
/// </summary>
[Browsable(false)]
public Collection<TypeEditor> Editors
{
// the collection is stored in the propertyTemplateSelector
get { return PropertyTemplateSelector.Editors; }
}
/// <summary>
/// The width of the property labels
/// </summary>
[Category(CATEGORY_APPEARANCE)]
public double LabelWidth
{
get { return (double)GetValue(LabelWidthProperty); }
set { SetValue(LabelWidthProperty, value); }
}
/// <summary>
/// Show read-only properties.
/// </summary>
[Category(CATEGORY_APPEARANCE)]
public bool ShowReadOnlyProperties
{
get { return (bool)GetValue(ShowReadOnlyPropertiesProperty); }
set { SetValue(ShowReadOnlyPropertiesProperty, value); }
}
/// <summary>
/// Organize the properties in tabs.
/// You should use the [Category("Tabname|Groupname")] attribute to define the tabs.
/// </summary>
[Category(CATEGORY_APPEARANCE)]
public bool ShowTabs
{
get { return (bool)GetValue(ShowTabsProperty); }
set { SetValue(ShowTabsProperty, value); }
}
/// <summary>
/// Show only declared properties (not inherited properties).
/// Specifies that only members declared at the level of the supplied type's hierarchy
/// should be considered. Inherited members are not considered.
/// </summary>
[Category(CATEGORY_APPEARANCE)]
public bool DeclaredOnly
{
get { return (bool)GetValue(DeclaredOnlyProperty); }
set { SetValue(DeclaredOnlyProperty, value); }
}
/// <summary>
/// Gets or sets SelectedObject.
/// </summary>
[Browsable(false)]
public object SelectedObject
{
get { return GetValue(SelectedObjectProperty); }
set { SetValue(SelectedObjectProperty, value); }
}
/// <summary>
/// Show enum properties as ComboBox or RadioButtonList.
/// </summary>
[Category(CATEGORY_APPEARANCE)]
public bool ShowBoolHeader
{
get { return (bool)GetValue(ShowBoolHeaderProperty); }
set { SetValue(ShowBoolHeaderProperty, value); }
}
/// <summary>
/// Gets or sets ShowCategoriesAs.
/// </summary>
[Category(CATEGORY_APPEARANCE)]
public ShowCategoriesAs ShowCategoriesAs
{
get { return (ShowCategoriesAs)GetValue(ShowCategoriesAsProperty); }
set { SetValue(ShowCategoriesAsProperty, value); }
}
/// <summary>
/// Gets or sets DefaultTabName.
/// </summary>
public string DefaultTabName
{
get { return (string)GetValue(DefaultTabNameProperty); }
set { SetValue(DefaultTabNameProperty, value); }
}
/// <summary>
/// Gets or sets DefaultCategoryName.
/// </summary>
public string DefaultCategoryName
{
get { return (string)GetValue(DefaultCategoryNameProperty); }
set { SetValue(DefaultCategoryNameProperty, value); }
}
/// <summary>
/// Gets or sets the alignment of property labels.
/// </summary>
public HorizontalAlignment LabelAlignment
{
get { return (HorizontalAlignment)GetValue(LabelAlignmentProperty); }
set { SetValue(LabelAlignmentProperty, value); }
}
/// <summary>
/// Implement the LocalizationService to translate the tab, category and property strings and tooltips
/// </summary>
[Browsable(false)]
public ILocalizationService LocalizationService
{
get { return (ILocalizationService)GetValue(LocalizationServiceProperty); }
set { SetValue(LocalizationServiceProperty, value); }
}
/// <summary>
/// The ImageProvider can be used to provide images to the Tab icons.
/// </summary>
[Browsable(false)]
public IImageProvider ImageProvider
{
get { return (IImageProvider)GetValue(ImageProviderProperty); }
set { SetValue(ImageProviderProperty, value); }
}
/// <summary>
/// Gets or sets the required attribute type.
/// If the required attribute type is set, only properties where this attribute is set will be shown.
/// </summary>
[Browsable(false)]
public Type RequiredAttribute
{
get { return (Type)GetValue(RequiredAttributeProperty); }
set { SetValue(RequiredAttributeProperty, value); }
}
/// <summary>
/// The PropertyTemplateSelector is used to select the DataTemplate for each PropertyViewModel
/// </summary>
[Browsable(false)]
public PropertyTemplateSelector PropertyTemplateSelector
{
get { return (PropertyTemplateSelector)GetValue(PropertyTemplateSelectorProperty); }
set { SetValue(PropertyTemplateSelectorProperty, value); }
}
/// <summary>
/// The CategoryTemplateSelector is used to select the DataTemplate for the CategoryViewModels
/// </summary>
[Browsable(false)]
public CategoryTemplateSelector CategoryTemplateSelector
{
get { return (CategoryTemplateSelector)GetValue(CategoryTemplateSelectorProperty); }
set { SetValue(CategoryTemplateSelectorProperty, value); }
}
/// <summary>
/// Gets or sets ErrorTemplate.
/// </summary>
public DataTemplate ErrorTemplate
{
get { return (DataTemplate)GetValue(ErrorTemplateProperty); }
set { SetValue(ErrorTemplateProperty, value); }
}
/// <summary>
/// Gets or sets WarningTemplate.
/// </summary>
public DataTemplate WarningTemplate
{
get { return (DataTemplate)GetValue(WarningTemplateProperty); }
set { SetValue(WarningTemplateProperty, value); }
}
/// <summary>
/// Gets rortemplate.
/// </summary>
public static RoutedEvent rortemplate
{
get { return PropertyValueChangedEvent; }
}
public IFileDialogService FileDialogService { get; set; }
public IFolderBrowserDialogService FolderBrowserDialogService { get; set; }
/// <summary>
/// The on apply template.
/// </summary>
public override void OnApplyTemplate()
{
if (tabControl == null)
{
tabControl = Template.FindName(PART_TABS, this) as TabControl;
}
if (contentControl == null)
{
contentControl = Template.FindName(PART_PAGE, this) as ContentControl;
}
if (grid == null)
{
grid = Template.FindName(PART_GRID, this) as Grid;
}
PropertyTemplateSelector.TemplateOwner = grid;
CategoryTemplateSelector.TemplateOwner = grid;
Loaded += PropertyEditor_Loaded;
Unloaded += PropertyEditor_Unloaded;
}
/// <summary>
/// The property editor_ loaded.
/// </summary>
/// <param name = "sender">
/// The sender.
/// </param>
/// <param name = "e">
/// The e.
/// </param>
private void PropertyEditor_Loaded(object sender, RoutedEventArgs e)
{
// Update the content of the control
UpdateContent();
}
/// <summary>
/// The property editor_ unloaded.
/// </summary>
/// <param name = "sender">
/// The sender.
/// </param>
/// <param name = "e">
/// The e.
/// </param>
private void PropertyEditor_Unloaded(object sender, RoutedEventArgs e)
{
// Unsubscribe all property change event handlers
ClearModel();
}
/// <summary>
/// The selected object changed.
/// </summary>
/// <param name = "d">
/// The d.
/// </param>
/// <param name = "e">
/// The e.
/// </param>
private static void SelectedObjectChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var pe = (PropertyEditor)d;
pe.UpdateContent();
}
/// <summary>
/// The selected objects changed.
/// </summary>
/// <param name = "d">
/// The d.
/// </param>
/// <param name = "e">
/// The e.
/// </param>
private static void SelectedObjectsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var pe = (PropertyEditor)d;
pe.UpdateContent();
}
/// <summary>
/// The property changed.
/// </summary>
public event EventHandler<PropertyValueChangedEventArgs> PropertyChanged
{
add { AddHandler(PropertyValueChangedEvent, value); }
remove { RemoveHandler(PropertyValueChangedEvent, value); }
}
/// <summary>
/// Invoke this method to raise a PropertyChanged event.
/// This event only makes sense when editing single objects (not IEnumerables).
/// </summary>
/// <param name = "propertyName">
/// The property Name.
/// </param>
/// <param name = "oldValue">
/// The old Value.
/// </param>
/// <param name = "newValue">
/// The new Value.
/// </param>
private void RaisePropertyChangedEvent(string propertyName, object oldValue, object newValue)
{
var args = new PropertyValueChangedEventArgs
{
PropertyName = propertyName,
OldValue = oldValue,
NewValue = newValue,
RoutedEvent = PropertyValueChangedEvent
};
RaiseEvent(args);
}
/// <summary>
/// The appearance changed.
/// </summary>
/// <param name = "d">
/// The d.
/// </param>
/// <param name = "e">
/// The e.
/// </param>
private static void AppearanceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((PropertyEditor)d).UpdateContent();
}
/// <summary>
/// Updates the content of the control
/// (after initialization and SelectedObject changes)
/// </summary>
public void UpdateContent()
{
if (!IsLoaded)
{
return;
}
if (tabControl == null)
{
throw new InvalidOperationException(PART_TABS + " cannot be found in the PropertyEditor template.");
}
if (contentControl == null)
{
throw new InvalidOperationException(PART_PAGE + " cannot be found in the PropertyEditor template.");
}
ClearModel();
// Get the property model (tabs, categories and properties)
if (SelectedObjects != null)
{
model = CreatePropertyModel(SelectedObjects, true);
}
else
{
model = CreatePropertyModel(SelectedObject, false);
}
if (ShowTabs)
{
tabControl.ItemsSource = model;
if (tabControl.Items.Count > 0)
{
tabControl.SelectedIndex = 0;
}
tabControl.Visibility = Visibility.Visible;
contentControl.Visibility = Visibility.Collapsed;
}
else
{
var tab = model != null && model.Count > 0 ? model[0] : null;
contentControl.Content = tab;
tabControl.Visibility = Visibility.Collapsed;
contentControl.Visibility = Visibility.Visible;
}
UpdatePropertyStates(SelectedObject);
UpdateErrorInfo();
}
/// <summary>
/// The clear model.
/// </summary>
private void ClearModel()
{
// Unsubscribe all property value changed events
if (model != null)
{
foreach (TabViewModel tab in model)
{
foreach (CategoryViewModel cat in tab.Categories)
{
foreach (PropertyViewModel prop in cat.Properties)
{
prop.UnsubscribeValueChanged();
}
}
}
}
model = null;
}
/// <summary>
/// This method takes an object Instance and creates the property model.
/// The properties are organized in a hierarchy
/// PropertyTab
/// PropertyCategory
/// Property|OptionalProperty|WideProperty|CheckBoxProperty
/// </summary>
/// <param name = "instance">
/// </param>
/// <param name = "isEnumerable">
/// </param>
/// <returns>
/// Collection of tab ViewModels
/// </returns>
public virtual IList<TabViewModel> CreatePropertyModel(object instance, bool isEnumerable)
{
if (instance == null)
{
return null;
}
// find the instance type
var instanceType = isEnumerable
? TypeHelper.FindBiggestCommonType(instance as IEnumerable)
: instance.GetType();
if (instanceType == null)
{
return null;
}
// find all properties of the instance type
var properties = isEnumerable
? TypeDescriptor.GetProperties(instanceType)
: TypeDescriptor.GetProperties(instance);
// The GetPropertyModel method does not return properties in a particular order,
// such as alphabetical or declaration order. Your code must not depend on the
// order in which properties are returned, because that order varies.
TabViewModel currentTabViewModel = null;
CategoryViewModel currentCategoryViewModel = null;
Type currentComponentType = null;
// Setting the default tab name
// Use the type name of the Instance as the default tab name
string tabName = DefaultTabName ?? instanceType.Name;
// Setting the default category name
string categoryName = DefaultCategoryName;
propertyMap.Clear();
int sortOrder = 0;
var result = new List<TabViewModel>();
foreach (PropertyDescriptor descriptor in properties)
{
if (descriptor == null)
{
continue;
}
// TODO: should not show attached dependency properties?
if (DeclaredOnly && descriptor.ComponentType != instanceType)
{
continue;
}
if (descriptor.ComponentType != currentComponentType)
{
categoryName = DefaultCategoryName;
tabName = DefaultTabName ?? descriptor.ComponentType.Name;
currentComponentType = descriptor.ComponentType;
}
// Skip properties marked with [Browsable(false)]
if (!descriptor.IsBrowsable)
{
continue;
}
// Read-only properties
if (!ShowReadOnlyProperties && descriptor.IsReadOnly)
{
continue;
}
// If RequiredAttribute is set, skip properties that don't have the given attribute
if (RequiredAttribute != null &&
!AttributeHelper.ContainsAttributeOfType(descriptor.Attributes, RequiredAttribute))
{
continue;
}
// The default value for an Enum-property is the first enum in the enumeration.
// If the first value happens to be filtered due to the attribute [Browsable(false)],
// the WPF-binding system ends up in an infinite loop when updating the bound value
// due to a PropertyChanged-call. We must therefore make sure that the initially selected
// value is one of the allowed values from the filtered enumeration.
if( descriptor.PropertyType.BaseType == typeof( Enum ) ) {
List<object> validEnumValues = Enum.GetValues( descriptor.PropertyType ).FilterOnBrowsableAttribute();
// Check if the enumeration that has all values hidden before accessing the first item.
if( validEnumValues.Count > 0 && !validEnumValues.Contains( descriptor.GetValue( instance ) ) ) {
descriptor.SetValue( instance, validEnumValues[0] );
}
}
// Create Property ViewModel
var propertyViewModel = PropertyViewModelFactory.CreateViewModel(instance, descriptor);
propertyViewModel.IsEnumerable = isEnumerable;
propertyViewModel.SubscribeValueChanged();
LocalizePropertyHeader(instanceType, propertyViewModel);
propertyMap.Add(propertyViewModel.Name, propertyViewModel);
propertyViewModel.PropertyChanged += OnPropertyChanged;
if (propertyViewModel.SortOrder == int.MinValue)
{
propertyViewModel.SortOrder = sortOrder;
}
sortOrder = propertyViewModel.SortOrder;
bool categoryFound = ParseTabAndCategory(descriptor, ref tabName, ref categoryName);
if (!categoryFound && UseDefaultCategoryNameForUncategorizedProperties)
{
categoryName = DefaultCategoryName;
tabName = DefaultTabName ?? descriptor.ComponentType.Name;
}
GetOrCreateTab(instanceType, result, tabName, sortOrder, ref currentTabViewModel,
ref currentCategoryViewModel);
GetOrCreateCategory(instanceType, categoryName, sortOrder, currentTabViewModel,
ref currentCategoryViewModel);
currentCategoryViewModel.Properties.Add(propertyViewModel);
}
// Check that properties used as optional properties are not Browsable
CheckOptionalProperties();
// Sort the model using a stable sort algorithm
return SortPropertyModel(result);
}
/// <summary>
/// The check optional properties.
/// </summary>
private void CheckOptionalProperties()
{
foreach (PropertyViewModel prop in propertyMap.Values)
{
var oprop = prop as OptionalPropertyViewModel;
if (oprop == null)
{
continue;
}
if (!string.IsNullOrEmpty(oprop.OptionalPropertyName))
{
if (propertyMap.ContainsKey(oprop.OptionalPropertyName))
{
Debug.WriteLine(String.Format("Optional properties ({0}) should not be [Browsable].",
oprop.OptionalPropertyName));
// remove OptionalPropertyName from the property bag...
// prop.IsOptional = false;
}
}
}
}
/// <summary>
/// The sort property model.
/// </summary>
/// <param name = "result">
/// The result.
/// </param>
/// <returns>
/// </returns>
private List<TabViewModel> SortPropertyModel(List<TabViewModel> result)
{
// Use LINQ to stable sort tabs, categories and properties.
// (important that it is a stable sort algorithm!)
var sortedResult = result.OrderBy(t => t.SortOrder).ToList();
foreach (TabViewModel tab in result)
{
tab.Sort();
foreach (CategoryViewModel cat in tab.Categories)
{
cat.Sort();
}
}
return sortedResult;
}
/// <summary>
/// If a CategoryAttributes is given as
/// [Category("TabA|GroupB")]
/// this will be parsed into tabName="TabA" and categoryName="GroupB"
/// If the CategoryAttribute is
/// [Category("GroupC")]
/// the method will not change tabName, but set categoryName="GroupC"
/// </summary>
/// <param name="descriptor">The descriptor.</param>
/// <param name="tabName">Name of the tab.</param>
/// <param name="categoryName">Name of the category.</param>
/// <returns>true if the descriptor contained a CategoryAttribute</returns>
private static bool ParseTabAndCategory(PropertyDescriptor descriptor, ref string tabName,
ref string categoryName)
{
var ca = AttributeHelper.GetFirstAttribute<CategoryAttribute>(descriptor);
if (ca == null || ca.Category == null || string.IsNullOrEmpty(ca.Category))
{
return false;
}
var items = ca.Category.Split('|');
if (items.Length == 2)
{
tabName = items[0];
categoryName = items[1];
}
if (items.Length == 1)
{
categoryName = items[0];
}
return true;
}
/// <summary>
/// The get or create category.
/// </summary>
/// <param name = "instanceType">
/// The instance type.
/// </param>
/// <param name = "categoryName">
/// The category name.
/// </param>
/// <param name = "sortOrder">
/// The sort order.
/// </param>
/// <param name = "currentTabViewModel">
/// The current tab view model.
/// </param>
/// <param name = "currentCategoryViewModel">
/// The current category view model.
/// </param>
private void GetOrCreateCategory(Type instanceType, string categoryName, int sortOrder,
TabViewModel currentTabViewModel,
ref CategoryViewModel currentCategoryViewModel)
{
if (currentCategoryViewModel == null || currentCategoryViewModel.Name != categoryName)
{
currentCategoryViewModel = currentTabViewModel.Categories.FirstOrDefault(c => c.Name == categoryName);
if (currentCategoryViewModel == null)
{
currentCategoryViewModel = new CategoryViewModel(categoryName, this) { SortOrder = sortOrder };
currentTabViewModel.Categories.Add(currentCategoryViewModel);
LocalizeCategoryHeader(instanceType, currentCategoryViewModel);
}
}
}
/// <summary>
/// The get or create tab.
/// </summary>
/// <param name = "instanceType">
/// The instance type.
/// </param>
/// <param name = "tabs">
/// The tabs.
/// </param>
/// <param name = "tabName">
/// The tab name.
/// </param>
/// <param name = "sortOrder">
/// The sort order.
/// </param>
/// <param name = "currentTabViewModel">
/// The current tab view model.
/// </param>
/// <param name = "currentCategoryViewModel">
/// The current category view model.
/// </param>
private void GetOrCreateTab(Type instanceType, ICollection<TabViewModel> tabs, string tabName, int sortOrder,
ref TabViewModel currentTabViewModel, ref CategoryViewModel currentCategoryViewModel)
{
if (currentTabViewModel == null || (currentTabViewModel.Name != tabName && ShowTabs))
{
currentTabViewModel = tabs.FirstOrDefault(t => t.Name == tabName);
if (currentTabViewModel == null)
{
// force to find/create a new category as well
currentCategoryViewModel = null;
currentTabViewModel = CreateTab(tabName);
currentTabViewModel.SortOrder = sortOrder;
tabs.Add(currentTabViewModel);
LocalizeTabHeader(instanceType, currentTabViewModel);
}
}
}
/// <summary>
/// The create tab.
/// </summary>
/// <param name = "tabName">
/// The tab name.
/// </param>
/// <returns>
/// </returns>
private TabViewModel CreateTab(string tabName)
{
var tab = new TabViewModel(tabName, this);
if (ImageProvider != null)
{
tab.Icon = ImageProvider.GetImage(SelectedObject.GetType(), Name);
}
return tab;
}
/// <summary>
/// Updates the property header and tooltip
/// </summary>
/// <param name = "instanceType">
/// Type of the object being edited
/// </param>
/// <param name = "propertyViewModel">
/// The property viewmodel
/// </param>
private void LocalizePropertyHeader(Type instanceType, PropertyViewModel propertyViewModel)
{
propertyViewModel.Header = GetLocalizedString(instanceType, propertyViewModel.Name);
propertyViewModel.ToolTip = GetLocalizedTooltip(instanceType, propertyViewModel.Name);
// [DisplayName(..)] and [Description(...)] attributes overrides the localized strings
var dna = AttributeHelper.GetFirstAttribute<DisplayNameAttribute>(propertyViewModel.Descriptor);
var da = AttributeHelper.GetFirstAttribute<DescriptionAttribute>(propertyViewModel.Descriptor);
if (dna != null)
{
propertyViewModel.Header = dna.DisplayName;
}
if (da != null)
{
propertyViewModel.ToolTip = da.Description;
}
}
/// <summary>
/// Updates the category (expander/groupbox) header and tooltip
/// </summary>
/// <param name = "instanceType">
/// </param>
/// <param name = "categoryViewModel">
/// </param>
private void LocalizeCategoryHeader(Type instanceType, CategoryViewModel categoryViewModel)
{
categoryViewModel.Header = GetLocalizedString(instanceType, categoryViewModel.Name);
categoryViewModel.ToolTip = GetLocalizedTooltip(instanceType, categoryViewModel.Name);
}
/// <summary>
/// Updates the tab header and tooltip
/// </summary>
/// <param name = "instanceType">
/// </param>
/// <param name = "tabViewModel">
/// </param>
private void LocalizeTabHeader(Type instanceType, TabViewModel tabViewModel)
{
tabViewModel.Header = GetLocalizedString(instanceType, tabViewModel.Name);
tabViewModel.ToolTip = GetLocalizedTooltip(instanceType, tabViewModel.Name);
}
/// <summary>
/// The OnPropertyChanged handler.
/// </summary>
/// <param name = "sender">
/// The sender.
/// </param>
/// <param name = "e">
/// The event arguments.
/// </param>
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
var property = sender as PropertyViewModel;
if (property != null && e.PropertyName == "Value")
{
RaisePropertyChangedEvent(property.PropertyName, property.OldValue, property.Value);
UpdateOptionalProperties(property);
}
if (e.PropertyName != "IsEnabled" && e.PropertyName != "IsVisible"
&& e.PropertyName != "PropertyError" && e.PropertyName != "PropertyWarning")
{
UpdatePropertyStates(SelectedObject);
UpdateErrorInfo();
}
}
/// <summary>
/// The UpdatePropertyStates method updates the properties IsEnabled when the instance being edited implements IPropertyStateUpdater.
/// </summary>
/// <param name = "instance">
/// The instance.
/// </param>
private void UpdatePropertyStates(object instance)
{
var psi = instance as IPropertyStateUpdater;
if (psi == null)
{
return;
}
var ps = new PropertyStateBag();
psi.UpdatePropertyStates(ps);
foreach (var ep in ps.EnabledProperties)
{
var p = propertyMap[ep.Key];
if (p != null && p.IsEnabled != ep.Value)
{
p.IsEnabled = ep.Value;
}
}
}
/// <summary>
/// The update error info.
/// </summary>
private void UpdateErrorInfo()
{
foreach (PropertyViewModel p in propertyMap.Values)
{
p.UpdateErrorInfo();
}
if (model != null)
{
foreach (TabViewModel tab in model)
{
tab.UpdateErrorInfo();
}
}
}
/// <summary>
/// Update IsEnabled on properties marked [Optional(..)]
/// </summary>
/// <param name = "propertyViewModel">
/// </param>
private void UpdateOptionalProperties(PropertyViewModel propertyViewModel)
{
foreach (PropertyViewModel prop in propertyMap.Values)
{
var oprop = prop as OptionalPropertyViewModel;
if (oprop == null)
{
continue;
}
if (oprop.OptionalPropertyName == propertyViewModel.PropertyName)
{
if (propertyViewModel.Value is bool)
{
oprop.IsEnabled = (bool)propertyViewModel.Value;
}
}
}
}
/// <summary>
/// The get localized string.
/// </summary>
/// <param name = "instanceType">
/// The instance type.
/// </param>
/// <param name = "key">
/// The key.
/// </param>
/// <returns>
/// The get localized string.
/// </returns>
private string GetLocalizedString(Type instanceType, string key)
{
string result = key;
if (LocalizationService != null)
{
result = LocalizationService.GetString(instanceType, key);
}
if (String.IsNullOrEmpty(result))
{
result = key;
}
return result;
}
/// <summary>
/// The get localized tooltip.
/// </summary>
/// <param name = "instanceType">
/// The instance type.
/// </param>
/// <param name = "key">
/// The key.
/// </param>
/// <returns>
/// The get localized tooltip.
/// </returns>
private object GetLocalizedTooltip(Type instanceType, string key)
{
object tooltip = null;
if (LocalizationService != null)
{
tooltip = LocalizationService.GetTooltip(instanceType, key);
}
if (tooltip is string)
{
var s = (string)tooltip;
s = s.Trim();
if (s.Length == 0)
{
tooltip = null;
}
}
return tooltip;
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.Key == Key.Enter)
{
var textBox = e.OriginalSource as TextBox;
if (textBox != null)
{
if (textBox.AcceptsReturn)
{
return;
}
var bindingExpression = textBox.GetBindingExpression(TextBox.TextProperty);
if (bindingExpression != null && bindingExpression.Status == System.Windows.Data.BindingStatus.Active)
{
bindingExpression.UpdateSource();
textBox.CaretIndex = textBox.Text.Length;
textBox.SelectAll();
}
}
}
}
}
/// <summary>
/// Event args for the PropertyValueChanged event
/// </summary>
public class PropertyValueChangedEventArgs : RoutedEventArgs
{
/// <summary>
/// Gets or sets PropertyName.
/// </summary>
public string PropertyName { get; set; }
/// <summary>
/// Gets or sets OldValue.
/// </summary>
public object OldValue { get; set; }
/// <summary>
/// Gets or sets NewValue.
/// </summary>
public object NewValue { get; set; }
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/PropertyEditor/PropertyEditor.cs | C# | gpl3 | 50,101 |
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Windows;
using System.Windows.Controls.Primitives;
namespace PropertyTools.Wpf
{
public class DefaultPropertyViewModelFactory : IPropertyViewModelFactory
{
protected readonly PropertyEditor owner;
/// <summary>
/// Initializes a new instance of the <see cref="DefaultPropertyViewModelFactory"/> class.
/// </summary>
/// <param name="owner">The owner PropertyEditor of the factory.
/// This is neccessary in order to get the PropertyTemplateSelector to work.</param>
public DefaultPropertyViewModelFactory(PropertyEditor owner)
{
this.owner = owner;
IsEnabledPattern = "Is{0}Enabled";
IsVisiblePattern = "Is{0}Visible";
UsePropertyPattern = "Use{0}";
}
/// <summary>
/// Gets or sets the IsEnabledPattern.
///
/// Example using a "Is{0}Enabled" pattern:
/// string City { get; set; }
/// bool IsCityEnabled { get; set; }
/// The state of the City property will be controlled by the IsCityEnabled property
/// </summary>
/// <value>The IsEnabledPattern.</value>
public string IsEnabledPattern { get; set; }
/// <summary>
/// Gets or sets the IsVisiblePattern.
///
/// Example using a "Is{0}Visible" pattern:
/// string City { get; set; }
/// bool IsCityVisible { get; set; }
/// The visibility state of the City property will be controlled by the IsCityVisible property
/// </summary>
/// <value>The IsVisiblePattern.</value>
public string IsVisiblePattern { get; set; }
/// <summary>
/// Gets or sets the UsePattern. This is used to create an "Optional" property.
///
/// Example using a "Use{0}" pattern:
/// string City { get; set; }
/// bool UseCity { get; set; }
/// The optional state of the City property will be controlled by the UseCity property
/// </summary>
/// <value>The UsePropertyPattern.</value>
public string UsePropertyPattern { get; set; }
#region IPropertyViewModelFactory Members
public virtual PropertyViewModel CreateViewModel(object instance, PropertyDescriptor descriptor)
{
PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(instance);
PropertyViewModel propertyViewModel = null;
string optionalPropertyName;
if (IsOptional(descriptor, out optionalPropertyName))
propertyViewModel = new OptionalPropertyViewModel(instance, descriptor, optionalPropertyName, owner);
if (IsPassword(descriptor))
propertyViewModel = new PasswordPropertyViewModel(instance, descriptor, owner);
if (IsResettable(descriptor))
propertyViewModel = new ResettablePropertyViewModel(instance, descriptor, owner);
if (UsePropertyPattern != null)
{
string usePropertyName = String.Format(UsePropertyPattern, descriptor.Name);
PropertyDescriptor useDescriptor = pdc.Find(usePropertyName, false);
if (useDescriptor != null)
propertyViewModel = new OptionalPropertyViewModel(instance, descriptor, useDescriptor, owner);
}
bool showHeader;
if (IsWide(descriptor, out showHeader))
propertyViewModel = new WidePropertyViewModel(instance, descriptor, showHeader, owner);
// If bool properties should be shown as checkbox only (no header label), we create a CheckBoxPropertyViewModel
if (descriptor.PropertyType == typeof(bool) && owner != null && !owner.ShowBoolHeader)
propertyViewModel = new CheckBoxPropertyViewModel(instance, descriptor, owner);
double min, max, largeChange, smallChange;
double tickFrequency;
bool snapToTicks;
TickPlacement tickPlacement;
if (IsSlidable(descriptor, out min, out max, out largeChange, out smallChange, out tickFrequency,
out snapToTicks, out tickPlacement))
propertyViewModel = new SlidablePropertyViewModel(instance, descriptor, owner)
{
SliderMinimum = min,
SliderMaximum = max,
SliderLargeChange = largeChange,
SliderSmallChange = smallChange,
SliderSnapToTicks = snapToTicks,
SliderTickFrequency = tickFrequency,
SliderTickPlacement = tickPlacement
};
// FilePath
string filter, defaultExtension;
bool useOpenDialog;
if (IsFilePath(descriptor, out filter, out defaultExtension, out useOpenDialog))
propertyViewModel = new FilePathPropertyViewModel(instance, descriptor, owner) { Filter = filter, DefaultExtension = defaultExtension, UseOpenDialog = useOpenDialog };
// DirectoryPath
if (IsDirectoryPath(descriptor))
propertyViewModel = new DirectoryPathPropertyViewModel(instance, descriptor, owner);
// Default property (using textbox)
if (propertyViewModel == null)
{
var tp = new PropertyViewModel(instance, descriptor, owner);
propertyViewModel = tp;
}
// Check if the AutoUpdatingText attribute is set (this will select the template that has a text binding using UpdateSourceTrigger=PropertyChanged)
if (IsAutoUpdatingText(descriptor))
propertyViewModel.AutoUpdateText = true;
propertyViewModel.FormatString = GetFormatString(descriptor);
//var ha = AttributeHelper.GetFirstAttribute<HeightAttribute>(descriptor);
//if (ha != null)
// propertyViewModel.Height = ha.Height;
propertyViewModel.Height = GetHeight(descriptor);
propertyViewModel.MaxLength = GetMaxLength(descriptor);
if (propertyViewModel.Height > 0 || IsMultilineText(descriptor))
{
propertyViewModel.AcceptsReturn = true;
propertyViewModel.TextWrapping = TextWrapping.Wrap;
}
var soa = AttributeHelper.GetFirstAttribute<SortOrderAttribute>(descriptor);
if (soa != null)
propertyViewModel.SortOrder = soa.SortOrder;
if (IsEnabledPattern != null)
{
string isEnabledName = String.Format(IsEnabledPattern, descriptor.Name);
propertyViewModel.IsEnabledDescriptor = pdc.Find(isEnabledName, false);
}
if (IsVisiblePattern != null)
{
string isVisibleName = String.Format(IsVisiblePattern, descriptor.Name);
propertyViewModel.IsVisibleDescriptor = pdc.Find(isVisibleName, false);
}
return propertyViewModel;
}
protected virtual bool IsMultilineText(PropertyDescriptor descriptor)
{
var dta = AttributeHelper.GetFirstAttribute<DataTypeAttribute>(descriptor);
return dta != null && dta.DataType==DataType.MultilineText;
}
#endregion
protected virtual bool IsDirectoryPath(PropertyDescriptor descriptor)
{
var dpa = AttributeHelper.GetFirstAttribute<DirectoryPathAttribute>(descriptor);
return dpa != null;
}
protected virtual bool IsFilePath(PropertyDescriptor descriptor, out string filter, out string defaultExtension, out bool useOpenDialog)
{
var fpa = AttributeHelper.GetFirstAttribute<FilePathAttribute>(descriptor);
filter = fpa != null ? fpa.Filter : null;
defaultExtension = fpa != null ? fpa.DefaultExtension : null;
useOpenDialog = fpa != null ? fpa.UseOpenDialog : true;
return fpa != null;
}
protected virtual bool IsOptional(PropertyDescriptor descriptor, out string optionalPropertyName)
{
optionalPropertyName = null;
// The following code is disabled (will make all Nullable types optional)
// if (descriptor.PropertyType.IsGenericType && descriptor.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
// return true;
// Return true only if the [Optional] attribute is set.
var oa = AttributeHelper.GetFirstAttribute<OptionalAttribute>(descriptor);
if (oa != null)
{
optionalPropertyName = oa.PropertyName;
return true;
}
return false;
}
protected virtual bool IsPassword(PropertyDescriptor descriptor)
{
var pa = AttributeHelper.GetFirstAttribute<DataTypeAttribute>(descriptor);
return (pa != null && pa.DataType == DataType.Password);
}
public virtual bool IsResettable(PropertyDescriptor descriptor)
{
var oa = AttributeHelper.GetFirstAttribute<ResettableAttribute>(descriptor);
if (oa != null)
return true;
return false;
}
protected virtual bool IsWide(PropertyDescriptor descriptor, out bool showHeader)
{
showHeader = true;
var wa = AttributeHelper.GetFirstAttribute<WidePropertyAttribute>(descriptor);
if (wa != null)
{
showHeader = wa.ShowHeader;
return true;
}
return false;
}
protected virtual bool IsSlidable(PropertyDescriptor descriptor, out double min, out double max,
out double largeChange, out double smallChange, out double tickFrequency,
out bool snapToTicks, out TickPlacement tickPlacement)
{
min = max = largeChange = smallChange = 0;
tickFrequency = 1;
snapToTicks = false;
tickPlacement = TickPlacement.None;
bool result = false;
var sa = AttributeHelper.GetFirstAttribute<SlidableAttribute>(descriptor);
if (sa != null)
{
min = sa.Minimum;
max = sa.Maximum;
largeChange = sa.LargeChange;
smallChange = sa.SmallChange;
snapToTicks = sa.SnapToTicks;
tickFrequency = sa.TickFrequency;
tickPlacement = sa.TickPlacement;
result = true;
}
return result;
}
protected virtual string GetFormatString(PropertyDescriptor descriptor)
{
var fsa = AttributeHelper.GetFirstAttribute<FormatStringAttribute>(descriptor);
if (fsa == null)
return null;
return fsa.FormatString;
}
protected virtual double GetHeight(PropertyDescriptor descriptor)
{
var ha = AttributeHelper.GetFirstAttribute<HeightAttribute>(descriptor);
if (ha == null)
return double.NaN;
return ha.Height;
}
protected virtual int GetMaxLength(PropertyDescriptor descriptor)
{
var ha = AttributeHelper.GetFirstAttribute<StringLengthAttribute>(descriptor);
if (ha == null)
return int.MaxValue;
return ha.MaximumLength;
}
protected virtual bool IsAutoUpdatingText(PropertyDescriptor descriptor)
{
var a = AttributeHelper.GetFirstAttribute<AutoUpdateTextAttribute>(descriptor);
return a != null;
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/PropertyEditor/DefaultPropertyViewModelFactory.cs | C# | gpl3 | 12,459 |
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="" file="BrowseForFolderDialog.cs">
//
// </copyright>
// <summary>
// Represents a common dialog box (Win32::SHBrowseForFolder()) that allows a user to select a folder.
// </summary>
//
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Interop;
namespace PropertyTools.Wpf.Shell32
{
/// <summary>
/// Represents a common dialog box (Win32::SHBrowseForFolder()) that allows a user to select a folder.
/// </summary>
public class BrowseForFolderDialog
{
#region Public Properties
/// <summary>
/// The browse info.
/// </summary>
private BROWSEINFOW browseInfo;
/// <summary>
/// Gets the current and or final selected folder path.
/// </summary>
public string SelectedFolder { get; protected set; }
/// <summary>
/// Gets or sets the string that is displayed above the tree view control in the dialog box (must set BEFORE calling ShowDialog()).
/// </summary>
public string Title
{
get { return BrowseInfo.lpszTitle; }
set { BrowseInfo.lpszTitle = value; }
}
/// <summary>
/// Gets or sets the initially selected folder path.
/// </summary>
public string InitialFolder { get; set; }
/// <summary>
/// Gets or sets the initially selected and expanded folder path. Overrides SelectedFolder.
/// </summary>
public string InitialExpandedFolder { get; set; }
/// <summary>
/// Gets or sets the text for the dialog's OK button.
/// </summary>
public string OKButtonText { get; set; }
/// <summary>
/// Provides direct access to the Win32::SHBrowseForFolder() BROWSEINFO structure used to create the dialog in ShowDialog().
/// </summary>
public BROWSEINFOW BrowseInfo
{
get { return browseInfo; }
protected set { browseInfo = value; }
}
/// <summary>
/// Provides direct access to the ulFlags field of the Win32::SHBrowseForFolder() structure used to create the dialog in ShowDialog().
/// </summary>
public BrowseInfoFlags BrowserDialogFlags
{
get { return BrowseInfo.ulFlags; }
set { BrowseInfo.ulFlags = value; }
}
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="BrowseForFolderDialog"/> class.
/// Constructs a BrowseForFolderDialog with default BrowseInfoFlags set to BIF_NEWDIALOGSTYLE.
/// </summary>
public BrowseForFolderDialog()
{
BrowseInfo = new BROWSEINFOW();
BrowseInfo.hwndOwner = IntPtr.Zero;
BrowseInfo.pidlRoot = IntPtr.Zero;
BrowseInfo.pszDisplayName = new string(' ', 260);
BrowseInfo.lpszTitle = "Select a folder:";
BrowseInfo.ulFlags = BrowseInfoFlags.BIF_NEWDIALOGSTYLE;
BrowseInfo.lpfn = new BrowseCallbackProc(BrowseEventHandler);
BrowseInfo.lParam = IntPtr.Zero;
BrowseInfo.iImage = -1;
}
#endregion
#region Public ShowDialog() Overloads
/// <summary>
/// Shows the dialog (Win32::SHBrowseForFolder()).
/// </summary>
public bool? ShowDialog()
{
return PInvokeSHBrowseForFolder(null);
}
/// <summary>
/// Shows the dialog (Win32::SHBrowseForFolder()) with its hwndOwner set to the handle of 'owner'.
/// </summary>
/// <param name="owner">
/// The owner.
/// </param>
public bool? ShowDialog(Window owner)
{
return PInvokeSHBrowseForFolder(owner);
}
#endregion
#region PInvoke Stuff
#region Delegates
/// <summary>
/// The browse callback proc.
/// </summary>
/// <param name="hwnd">
/// The hwnd.
/// </param>
/// <param name="uMsg">
/// The u msg.
/// </param>
/// <param name="lParam">
/// The l param.
/// </param>
/// <param name="lpData">
/// The lp data.
/// </param>
public delegate int BrowseCallbackProc(IntPtr hwnd, MessageFromBrowser uMsg, IntPtr lParam, IntPtr lpData);
#endregion
#region BrowseInfoFlags enum
/// <summary>
/// The browse info flags.
/// </summary>
[Flags]
public enum BrowseInfoFlags : uint
{
/// <summary>
/// No specified BIF_xxx flags.
/// </summary>
BIF_None = 0x0000,
/// <summary>
/// Only return file system directories. If the user selects folders that are not part of the file system, the OK button is grayed.
/// </summary>
BIF_RETURNONLYFSDIRS = 0x0001, // For finding a folder to start document searching
/// <summary>
/// Do not include network folders below the domain level in the dialog box's tree view control.
/// </summary>
BIF_DONTGOBELOWDOMAIN = 0x0002, // For starting the Find Computer
/// <summary>
/// Include a status area in the dialog box.
/// </summary>
BIF_STATUSTEXT = 0x0004, // Top of the dialog has 2 lines of text for BROWSEINFO.lpszTitle and one line if
// this flag is set. Passing the message BFFM_SETSTATUSTEXTA to the hwnd can set the
// rest of the text. This is not used with BIF_USENEWUI and BROWSEINFO.lpszTitle gets
// all three lines of text.
/// <summary>
/// Only return file system ancestors. An ancestor is a subfolder that is beneath the root folder in the namespace hierarchy.
/// </summary>
BIF_RETURNFSANCESTORS = 0x0008,
/// <summary>
/// Include an edit control in the browse dialog box that allows the user to type the name of an item.
/// </summary>
BIF_EDITBOX = 0x0010, // Add an editbox to the dialog
/// <summary>
/// If the user types an invalid name into the edit box, the browse dialog box will call the application's BrowseCallbackProc with the BFFM_VALIDATEFAILED message.
/// </summary>
BIF_VALIDATE = 0x0020, // insist on valid result (or CANCEL)
/// <summary>
/// Use the new user interface. Setting this flag provides the user with a larger dialog box that can be resized.
/// </summary>
BIF_NEWDIALOGSTYLE = 0x0040, // Use the new dialog layout with the ability to resize
// Caller needs to call OleInitialize() before using this API
/// <summary>
/// Use the new user interface, including an edit box. This flag is equivalent to BIF_EDITBOX | BIF_NEWDIALOGSTYLE.
/// </summary>
BIF_USENEWUI = BIF_NEWDIALOGSTYLE | BIF_EDITBOX,
/// <summary>
/// The browse dialog box can display URLs. The BIF_USENEWUI and BIF_BROWSEINCLUDEFILES flags must also be set.
/// </summary>
BIF_BROWSEINCLUDEURLS = 0x0080, // Allow URLs to be displayed or entered. (Requires BIF_USENEWUI)
/// <summary>
/// When combined with BIF_NEWDIALOGSTYLE, adds a usage hint to the dialog box in place of the edit box.
/// </summary>
BIF_UAHINT = 0x0100,
// Add a UA hint to the dialog, in place of the edit box. May not be combined with BIF_EDITBOX
/// <summary>
/// Do not include the New Folder button in the browse dialog box.
/// </summary>
BIF_NONEWFOLDERBUTTON = 0x0200,
// Do not add the "New Folder" button to the dialog. Only applicable with BIF_NEWDIALOGSTYLE.
/// <summary>
/// When the selected item is a shortcut, return the PIDL of the shortcut itself rather than its target.
/// </summary>
BIF_NOTRANSLATETARGETS = 0x0400, // don't traverse target as shortcut
/// <summary>
/// Only return computers. If the user selects anything other than a computer, the OK button is grayed.
/// </summary>
BIF_BROWSEFORCOMPUTER = 0x1000, // Browsing for Computers.
/// <summary>
/// Only allow the selection of printers. If the user selects anything other than a printer, the OK button is grayed.
/// </summary>
BIF_BROWSEFORPRINTER = 0x2000, // Browsing for Printers
/// <summary>
/// The browse dialog box will display files as well as folders.
/// </summary>
BIF_BROWSEINCLUDEFILES = 0x4000, // Browsing for Everything
/// <summary>
/// The browse dialog box can display shareable resources on remote systems.
/// </summary>
BIF_SHAREABLE = 0x8000 // sharable resources displayed (remote shares, requires BIF_USENEWUI)
}
#endregion
// message from browser
#region MessageFromBrowser enum
/// <summary>
/// The message from browser.
/// </summary>
public enum MessageFromBrowser : uint
{
/// <summary>
/// The dialog box has finished initializing.
/// </summary>
BFFM_INITIALIZED = 1,
/// <summary>
/// The selection has changed in the dialog box.
/// </summary>
BFFM_SELCHANGED = 2,
/// <summary>
/// (ANSI) The user typed an invalid name into the dialog's edit box. A nonexistent folder is considered an invalid name.
/// </summary>
BFFM_VALIDATEFAILEDA = 3,
/// <summary>
/// (Unicode) The user typed an invalid name into the dialog's edit box. A nonexistent folder is considered an invalid name.
/// </summary>
BFFM_VALIDATEFAILEDW = 4,
/// <summary>
/// An IUnknown interface is available to the dialog box.
/// </summary>
BFFM_IUNKNOWN = 5
}
#endregion
// messages to browser
#region MessageToBrowser enum
/// <summary>
/// The message to browser.
/// </summary>
public enum MessageToBrowser : uint
{
/// <summary>
/// Win32 API macro - start of user defined window message range.
/// </summary>
WM_USER = 0x0400,
/// <summary>
/// (ANSI) Sets the status text. Set lpData to point to a null-terminated string with the desired text.
/// </summary>
BFFM_SETSTATUSTEXTA = WM_USER + 100,
/// <summary>
/// Enables or disables the dialog box's OK button. lParam - To enable, set to a nonzero value. To disable, set to zero.
/// </summary>
BFFM_ENABLEOK = WM_USER + 101,
/// <summary>
/// (ANSI) Specifies the path of a folder to select.
/// </summary>
BFFM_SETSELECTIONA = WM_USER + 102,
/// <summary>
/// (Unicode) Specifies the path of a folder to select.
/// </summary>
BFFM_SETSELECTIONW = WM_USER + 103,
/// <summary>
/// (Unicode) Sets the status text. Set lpData to point to a null-terminated string with the desired text.
/// </summary>
BFFM_SETSTATUSTEXTW = WM_USER + 104,
/// <summary>
/// Sets the text that is displayed on the dialog box's OK button.
/// </summary>
BFFM_SETOKTEXT = WM_USER + 105, // Unicode only
/// <summary>
/// Specifies the path of a folder to expand in the Browse dialog box.
/// </summary>
BFFM_SETEXPANDED = WM_USER + 106 // Unicode only
}
#endregion
/// <summary>
/// The p invoke sh browse for folder.
/// </summary>
/// <param name="owner">
/// The owner.
/// </param>
/// <returns>
/// </returns>
private bool? PInvokeSHBrowseForFolder(Window owner)
{
WindowInteropHelper windowhelper;
if (null != owner)
{
windowhelper = new WindowInteropHelper(owner);
BrowseInfo.hwndOwner = windowhelper.Handle;
}
IntPtr pidl = SHBrowseForFolderW(browseInfo);
if (IntPtr.Zero != pidl)
{
var pathsb = new StringBuilder(260);
if (SHGetPathFromIDList(pidl, pathsb))
{
SelectedFolder = pathsb.ToString();
Marshal.FreeCoTaskMem(pidl);
return true;
}
}
return false;
}
/// <summary>
/// The browse event handler.
/// </summary>
/// <param name="hwnd">
/// The hwnd.
/// </param>
/// <param name="uMsg">
/// The u msg.
/// </param>
/// <param name="lParam">
/// The l param.
/// </param>
/// <param name="lpData">
/// The lp data.
/// </param>
/// <returns>
/// The browse event handler.
/// </returns>
private int BrowseEventHandler(IntPtr hwnd, MessageFromBrowser uMsg, IntPtr lParam, IntPtr lpData)
{
switch (uMsg)
{
case MessageFromBrowser.BFFM_INITIALIZED:
{
// The dialog box has finished initializing.
// lParam Not used, value is NULL.
if (!string.IsNullOrEmpty(InitialExpandedFolder))
{
SendMessageW(hwnd, MessageToBrowser.BFFM_SETEXPANDED, new IntPtr(1), InitialExpandedFolder);
}
else if (!string.IsNullOrEmpty(InitialFolder))
{
SendMessageW(hwnd, MessageToBrowser.BFFM_SETSELECTIONW, new IntPtr(1), InitialFolder);
}
if (!string.IsNullOrEmpty(OKButtonText))
{
SendMessageW(hwnd, MessageToBrowser.BFFM_SETOKTEXT, new IntPtr(1), OKButtonText);
}
break;
}
case MessageFromBrowser.BFFM_SELCHANGED:
{
// The selection has changed in the dialog box.
// lParam A pointer to an item identifier list (PIDL) identifying the newly selected item.
var pathsb = new StringBuilder(260);
if (SHGetPathFromIDList(lParam, pathsb))
{
SelectedFolder = pathsb.ToString();
}
break;
}
case MessageFromBrowser.BFFM_VALIDATEFAILEDA:
{
// ANSI
// The user typed an invalid name into the dialog's edit box. A nonexistent folder is considered an invalid name.
// lParam A pointer to a string containing the invalid name. An application can use this data in an error dialog informing the user that the name was not valid.
// Return zero to dismiss the dialog or nonzero to keep the dialog displayed
break;
}
case MessageFromBrowser.BFFM_VALIDATEFAILEDW:
{
// Unicode
// The user typed an invalid name into the dialog's edit box. A nonexistent folder is considered an invalid name.
// lParam A pointer to a string containing the invalid name. An application can use this data in an error dialog informing the user that the name was not valid.
// Return zero to dismiss the dialog or nonzero to keep the dialog displayed
break;
}
case MessageFromBrowser.BFFM_IUNKNOWN:
{
// An IUnknown interface is available to the dialog box.
// lParam A pointer to an IUnknown interface.
break;
}
}
return 0;
}
/// <summary>
/// The sh browse for folder w.
/// </summary>
/// <param name="bi">
/// The bi.
/// </param>
/// <returns>
/// </returns>
[DllImport("shell32.dll")]
private static extern IntPtr SHBrowseForFolderW([MarshalAs(UnmanagedType.LPStruct), In, Out] BROWSEINFOW bi);
/// <summary>
/// The sh get path from id list.
/// </summary>
/// <param name="pidl">
/// The pidl.
/// </param>
/// <param name="path">
/// The path.
/// </param>
/// <returns>
/// The sh get path from id list.
/// </returns>
[DllImport("shell32.dll")]
private static extern bool SHGetPathFromIDList(IntPtr pidl, StringBuilder path);
/// <summary>
/// The send message w.
/// </summary>
/// <param name="hWnd">
/// The h wnd.
/// </param>
/// <param name="Msg">
/// The msg.
/// </param>
/// <param name="wParam">
/// The w param.
/// </param>
/// <param name="lParam">
/// The l param.
/// </param>
/// <returns>
/// </returns>
[DllImport("user32.dll")]
public static extern IntPtr SendMessageW(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
/// <summary>
/// The send message w.
/// </summary>
/// <param name="hWnd">
/// The h wnd.
/// </param>
/// <param name="msg">
/// The msg.
/// </param>
/// <param name="wParam">
/// The w param.
/// </param>
/// <param name="str">
/// The str.
/// </param>
/// <returns>
/// </returns>
[DllImport("user32.dll")]
public static extern IntPtr SendMessageW(IntPtr hWnd, MessageToBrowser msg, IntPtr wParam,
[MarshalAs(UnmanagedType.LPWStr)] string str);
/// <summary>
/// The browseinfow.
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public class BROWSEINFOW
{
/// <summary>
/// A handle to the owner window for the dialog box.
/// </summary>
public IntPtr hwndOwner;
/// <summary>
/// A pointer to an item identifier list (PIDL) specifying the location of the root folder from which to start browsing.
/// </summary>
public IntPtr pidlRoot; // PCIDLIST_ABSOLUTE
/// <summary>
/// The address of a buffer to receive the display name of the folder selected by the user. The size of this buffer is assumed to be MAX_PATH characters.
/// </summary>
public string pszDisplayName; // Output parameter! (length must be >= MAX_PATH)
/// <summary>
/// The address of a null-terminated string that is displayed above the tree view control in the dialog box.
/// </summary>
public string lpszTitle;
/// <summary>
/// Flags specifying the options for the dialog box.
/// </summary>
public BrowseInfoFlags ulFlags;
/// <summary>
/// A BrowseCallbackProc delegate that the dialog box calls when an event occurs.
/// </summary>
public BrowseCallbackProc lpfn;
/// <summary>
/// An application-defined value that the dialog box passes to the BrowseCallbackProc delegate, if one is specified.
/// </summary>
public IntPtr lParam;
/// <summary>
/// A variable to receive the image associated with the selected folder. The image is specified as an index to the system image list.
/// </summary>
public int iImage; // Output parameter!
}
#endregion
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Dialogs/Shell32/BrowseForFolderDialog.cs | C# | gpl3 | 21,634 |
using System.Collections.Generic;
using System.Windows;
namespace PropertyTools.Wpf
{
/// <summary>
/// Wizard dialog
/// Todo: Win7 style
/// </summary>
public partial class WizardDialog : Window
{
public static readonly DependencyProperty CurrentPageProperty =
DependencyProperty.Register("CurrentPage", typeof (int), typeof (WizardDialog),
new UIPropertyMetadata(-1, CurrentPage_Changed));
public static readonly DependencyProperty PagesProperty =
DependencyProperty.Register("Pages", typeof (List<object>), typeof (WizardDialog),
new UIPropertyMetadata(null));
public WizardDialog()
{
InitializeComponent();
Pages = new List<object>();
Background = SystemColors.ControlBrush;
NextButton.Click += NextButton_Click;
BackButton.Click += BackButton_Click;
FinishButton.Click += FinishButton_Click;
CancelButton.Click += CancelButton_Click;
Loaded += WizardDialog_Loaded;
}
public int CurrentPage
{
get { return (int) GetValue(CurrentPageProperty); }
set { SetValue(CurrentPageProperty, value); }
}
public List<object> Pages
{
get { return (List<object>) GetValue(PagesProperty); }
set { SetValue(PagesProperty, value); }
}
private static void CurrentPage_Changed(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var d = sender as WizardDialog;
d.BindPage();
}
private void FinishButton_Click(object sender, RoutedEventArgs e)
{
DialogResult = true;
Close();
}
private void NextButton_Click(object sender, RoutedEventArgs e)
{
CurrentPage++;
}
private void BackButton_Click(object sender, RoutedEventArgs e)
{
CurrentPage--;
}
private void WizardDialog_Loaded(object sender, RoutedEventArgs e)
{
CurrentPage = 0;
}
private void BindPage()
{
if (CurrentPage < 0 || CurrentPage >= Pages.Count)
propertyControl1.DataContext = null;
else
propertyControl1.DataContext = Pages[CurrentPage];
BackButton.IsEnabled = CurrentPage > 0;
NextButton.IsEnabled = CurrentPage + 1 < Pages.Count;
FinishButton.IsEnabled = CurrentPage == Pages.Count - 1;
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Dialogs/WizardDialog.xaml.cs | C# | gpl3 | 2,840 |
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Media;
namespace PropertyTools.Wpf
{
/// <summary>
/// A basic About Dialog (inspired by Google)
/// </summary>
public partial class AboutDialog : Window
{
private readonly AboutViewModel vm;
public AboutDialog(Window owner)
{
this.Owner = owner;
this.Icon = owner.Icon;
InitializeComponent();
vm = new AboutViewModel(Assembly.GetCallingAssembly());
DataContext = vm;
}
/// <summary>
/// Sets the image used in the about dialog.
/// Example:
/// d.Image = new BitmapImage(new Uri(@"pack://application:,,,/AssemblyName;component/Images/about.png"));
/// </summary>
/// <value>The image.</value>
public ImageSource Image
{
set { vm.Image = value; }
}
/// <summary>
/// Sets the update status.
/// </summary>
/// <value>The update status.</value>
public string UpdateStatus
{
set { vm.UpdateStatus = value; }
}
private void Ok_Click(object sender, RoutedEventArgs e)
{
Close();
}
private void SystemInfo_Click(object sender, RoutedEventArgs e)
{
Process.Start("MsInfo32.exe");
}
private void Copy_Click(object sender, RoutedEventArgs e)
{
Clipboard.SetText(vm.GetReport());
}
}
public class AboutViewModel
{
public Assembly Assembly { get; set; }
public FileVersionInfo FileVersionInfo { get; set; }
public FileInfo FileInfo { get; set; }
public AboutViewModel(Assembly a)
{
if (a == null)
throw new InvalidOperationException();
if (a.Location == null)
throw new InvalidOperationException();
FileVersionInfo = FileVersionInfo.GetVersionInfo(a.Location);
FileInfo = new FileInfo(FileVersionInfo.FileName);
var va = (AssemblyVersionAttribute[])a.GetCustomAttributes(typeof(AssemblyVersionAttribute),true);
if (va != null && va.Length > 0)
{
AssemblyVersion = va[0].Version;
}
}
public ImageSource Image { get; set; }
public string AssemblyVersion { get; private set; }
public string ProductName { get { return FileVersionInfo.ProductName; } }
public string Version { get { return FileVersionInfo.ProductVersion; } }
public string Copyright { get { return FileVersionInfo.LegalCopyright; } }
public string Comments { get { return FileVersionInfo.Comments; } }
public string Company { get { return FileVersionInfo.CompanyName; } }
public string FileVersion { get { return FileVersionInfo.FileVersion; } }
public string BuildTime { get { return FileInfo.LastWriteTime.ToString(); } }
public string FileName { get { return Path.GetFullPath(FileVersionInfo.FileName); } }
public string Platform { get { return Environment.OSVersion.Platform.ToString(); } }
public string OSVersion { get { return Environment.OSVersion.Version.ToString(); } }
public string ServicePack { get { return Environment.OSVersion.ServicePack; } }
public string CLRversion { get { return Environment.Version.ToString(); } }
public string MachineName { get { return Environment.MachineName; } }
public int Processors { get { return Environment.ProcessorCount; } }
public string User { get { return Environment.UserName; } }
public string Domain { get { return Environment.UserDomainName; } }
public string UpdateStatus { get; set; }
public string GetReport()
{
var sb = new StringBuilder();
sb.AppendFormat("Product: {0}", ProductName);
sb.AppendLine();
sb.AppendFormat("Product Version: {0}", Version);
sb.AppendLine();
sb.AppendFormat("Copyright: {0}", Copyright);
sb.AppendLine();
sb.AppendFormat("Company: {0}", Company);
sb.AppendLine();
sb.AppendFormat("Assembly version: {0}", AssemblyVersion);
sb.AppendLine();
sb.AppendFormat("File version: {0}", FileVersion);
sb.AppendLine();
sb.AppendFormat("Build time: {0}", BuildTime);
sb.AppendLine();
sb.AppendFormat("FileName: {0}", FileName);
sb.AppendLine();
sb.AppendFormat("Platform: {0}", Platform);
sb.AppendLine();
sb.AppendFormat("OS version: {0}", OSVersion);
sb.AppendLine();
sb.AppendFormat("Service Pack: {0}", ServicePack);
sb.AppendLine();
sb.AppendFormat("CLR version: {0}", CLRversion);
sb.AppendLine();
sb.AppendFormat("Machine name: {0}", MachineName);
sb.AppendLine();
sb.AppendFormat("Processors: {0}", Processors);
sb.AppendLine();
sb.AppendFormat("User: {0}", User);
sb.AppendLine();
sb.AppendFormat("Domain: {0}", Domain);
return sb.ToString();
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Dialogs/AboutDialog.xaml.cs | C# | gpl3 | 5,577 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Windows;
namespace PropertyTools.Wpf
{
/// <summary>
/// Automatic Property Dialog
/// Set the DataContext of the Dialog to the instance you want to edit.
/// </summary>
public partial class PropertyDialog : Window
{
public PropertyDialog()
{
InitializeComponent();
MaxWidth = SystemParameters.PrimaryScreenWidth*0.9;
MaxHeight = SystemParameters.PrimaryScreenHeight*0.9;
ApplyButton.Visibility = Visibility.Collapsed;
CloseButton.Visibility = Visibility.Collapsed;
HelpButton.Visibility = Visibility.Collapsed;
DataContextChanged += PropertyDialog_DataContextChanged;
}
#region Cinch
/// <summary>
/// This stores the current "copy" of the object.
/// If it is non-null, then we are in the middle of an
/// editable operation.
/// </summary>
// private Dictionary<string, object> _savedState;
/// <summary>
/// This is used to clone the object.
/// Override the method to provide a more efficient clone.
/// The default implementation simply reflects across
/// the object copying every field.
/// </summary>
/// <returns>Clone of current object</returns>
protected virtual Dictionary<string, object> GetFieldValues(object obj)
{
return obj.GetType().GetProperties(BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance)
.Where(pi => pi.CanRead && pi.GetIndexParameters().Length == 0)
.Select(pi => new {Key = pi.Name, Value = pi.GetValue(obj, null)})
.ToDictionary(k => k.Key, k => k.Value);
}
/// <summary>
/// This restores the state of the current object from the passed clone object.
/// </summary>
/// <param name="fieldValues">Object to restore state from</param>
/// <param name="obj"></param>
protected virtual void RestoreFieldValues(Dictionary<string, object> fieldValues, object obj)
{
foreach (PropertyInfo pi in obj.GetType().GetProperties(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(pi => pi.CanWrite && pi.GetIndexParameters().Length == 0))
{
object value;
if (fieldValues.TryGetValue(pi.Name, out value))
pi.SetValue(obj, value, null);
else
{
Debug.WriteLine("Failed to restore property " +
pi.Name + " from cloned values, property not found in Dictionary.");
}
}
}
#endregion
public PropertyEditor PropertyControl
{
get { return propertyControl1; }
}
public bool CanApply
{
get { return ApplyButton.Visibility == Visibility.Visible; }
set { ApplyButton.Visibility = value ? Visibility.Visible : Visibility.Collapsed; }
}
private void PropertyDialog_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
BeginEdit();
}
private void BeginEdit()
{
var editableDataContext = DataContext as IEditableObject;
if (editableDataContext != null)
{
editableDataContext.BeginEdit();
}
else
{
PropertyControl.DataContext = MemberwiseClone(DataContext);
}
}
private void EndEdit()
{
var editableDataContext = DataContext as IEditableObject;
if (editableDataContext != null)
{
editableDataContext.EndEdit();
}
else
{
CommitChanges();
}
}
private void CancelEdit()
{
var editableDataContext = DataContext as IEditableObject;
if (editableDataContext != null)
{
editableDataContext.CancelEdit();
}
}
private static object MemberwiseClone(object src)
{
var t = src.GetType();
var clone = Activator.CreateInstance(t);
foreach (
PropertyInfo pi in t.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(pi => pi.CanWrite && pi.GetIndexParameters().Length == 0))
{
pi.SetValue(clone, pi.GetValue(src, null), null);
}
return clone;
}
private void CommitChanges()
{
// copy changes from cloned object (stored in PropertyEditor.DataContext)
// to the original object (stored in DataContext)
var clone = PropertyControl.DataContext;
if (clone==null)
return;
foreach (
var pi in
clone.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(pi => pi.CanWrite && pi.GetIndexParameters().Length == 0))
{
var newValue = pi.GetValue(clone, null);
var oldValue = pi.GetValue(DataContext, null);
if (oldValue==null && newValue==null)
continue;
if (oldValue!=null && !oldValue.Equals(newValue))
pi.SetValue(DataContext, newValue, null);
}
}
private void OkButton_Click(object sender, RoutedEventArgs e)
{
// todo: only if modal dialog
DialogResult = true;
EndEdit();
Close();
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
// RestoreFieldValues(_savedState, DataContext);
// todo: only if modal dialog
DialogResult = false;
CancelEdit();
Close();
}
private void ApplyButton_Click(object sender, RoutedEventArgs e)
{
CommitChanges();
}
private void CloseButton_Click(object sender, RoutedEventArgs e)
{
Close();
}
private void HelpButton_Click(object sender, RoutedEventArgs e)
{
}
}
} | zzgaminginc-pointofssale | Lib/PropertyTools.Wpf/Dialogs/PropertyDialog.xaml.cs | C# | gpl3 | 6,914 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Timers;
using System.Windows.Threading;
namespace UIControls {
public enum SearchMode {
Instant,
Delayed,
}
public class SearchTextBox : TextBox {
public static DependencyProperty LabelTextProperty =
DependencyProperty.Register(
"LabelText",
typeof(string),
typeof(SearchTextBox));
public static DependencyProperty LabelTextColorProperty =
DependencyProperty.Register(
"LabelTextColor",
typeof(Brush),
typeof(SearchTextBox));
public static DependencyProperty SearchModeProperty =
DependencyProperty.Register(
"SearchMode",
typeof(SearchMode),
typeof(SearchTextBox),
new PropertyMetadata(SearchMode.Instant));
private static DependencyPropertyKey HasTextPropertyKey =
DependencyProperty.RegisterReadOnly(
"HasText",
typeof(bool),
typeof(SearchTextBox),
new PropertyMetadata());
public static DependencyProperty HasTextProperty = HasTextPropertyKey.DependencyProperty;
private static DependencyPropertyKey IsMouseLeftButtonDownPropertyKey =
DependencyProperty.RegisterReadOnly(
"IsMouseLeftButtonDown",
typeof(bool),
typeof(SearchTextBox),
new PropertyMetadata());
public static DependencyProperty IsMouseLeftButtonDownProperty = IsMouseLeftButtonDownPropertyKey.DependencyProperty;
public static DependencyProperty SearchEventTimeDelayProperty =
DependencyProperty.Register(
"SearchEventTimeDelay",
typeof(Duration),
typeof(SearchTextBox),
new FrameworkPropertyMetadata(
new Duration(new TimeSpan(0, 0, 0, 0, 500)),
new PropertyChangedCallback(OnSearchEventTimeDelayChanged)));
public static readonly RoutedEvent SearchEvent =
EventManager.RegisterRoutedEvent(
"Search",
RoutingStrategy.Bubble,
typeof(RoutedEventHandler),
typeof(SearchTextBox));
static SearchTextBox() {
DefaultStyleKeyProperty.OverrideMetadata(
typeof(SearchTextBox),
new FrameworkPropertyMetadata(typeof(SearchTextBox)));
}
private DispatcherTimer searchEventDelayTimer;
public SearchTextBox()
: base() {
searchEventDelayTimer = new DispatcherTimer();
searchEventDelayTimer.Interval = SearchEventTimeDelay.TimeSpan;
searchEventDelayTimer.Tick += new EventHandler(OnSeachEventDelayTimerTick);
}
void OnSeachEventDelayTimerTick(object o, EventArgs e) {
searchEventDelayTimer.Stop();
RaiseSearchEvent();
}
static void OnSearchEventTimeDelayChanged(
DependencyObject o, DependencyPropertyChangedEventArgs e) {
SearchTextBox stb = o as SearchTextBox;
if (stb != null) {
stb.searchEventDelayTimer.Interval = ((Duration)e.NewValue).TimeSpan;
stb.searchEventDelayTimer.Stop();
}
}
protected override void OnTextChanged(TextChangedEventArgs e) {
base.OnTextChanged(e);
HasText = Text.Length != 0;
if (SearchMode == SearchMode.Instant) {
searchEventDelayTimer.Stop();
searchEventDelayTimer.Start();
}
}
public override void OnApplyTemplate() {
base.OnApplyTemplate();
Border iconBorder = GetTemplateChild("PART_SearchIconBorder") as Border;
if (iconBorder != null) {
iconBorder.MouseLeftButtonDown += new MouseButtonEventHandler(IconBorder_MouseLeftButtonDown);
iconBorder.MouseLeftButtonUp += new MouseButtonEventHandler(IconBorder_MouseLeftButtonUp);
iconBorder.MouseLeave += new MouseEventHandler(IconBorder_MouseLeave);
}
}
private void IconBorder_MouseLeftButtonDown(object obj, MouseButtonEventArgs e) {
IsMouseLeftButtonDown = true;
}
private void IconBorder_MouseLeftButtonUp(object obj, MouseButtonEventArgs e) {
if (!IsMouseLeftButtonDown) return;
if (HasText && SearchMode == SearchMode.Instant) {
this.Text = "";
}
if (HasText && SearchMode == SearchMode.Delayed) {
RaiseSearchEvent();
}
IsMouseLeftButtonDown = false;
}
private void IconBorder_MouseLeave(object obj, MouseEventArgs e) {
IsMouseLeftButtonDown = false;
}
protected override void OnKeyDown(KeyEventArgs e) {
if (e.Key == Key.Escape && SearchMode == SearchMode.Instant) {
this.Text = "";
}
else if ((e.Key == Key.Return || e.Key == Key.Enter) &&
SearchMode == SearchMode.Delayed) {
RaiseSearchEvent();
}
else {
base.OnKeyDown(e);
}
}
private void RaiseSearchEvent() {
RoutedEventArgs args = new RoutedEventArgs(SearchEvent);
RaiseEvent(args);
}
public string LabelText {
get { return (string)GetValue(LabelTextProperty); }
set { SetValue(LabelTextProperty, value); }
}
public Brush LabelTextColor {
get { return (Brush)GetValue(LabelTextColorProperty); }
set { SetValue(LabelTextColorProperty, value); }
}
public SearchMode SearchMode {
get { return (SearchMode)GetValue(SearchModeProperty); }
set { SetValue(SearchModeProperty, value); }
}
public bool HasText {
get { return (bool)GetValue(HasTextProperty); }
private set { SetValue(HasTextPropertyKey, value); }
}
public Duration SearchEventTimeDelay {
get { return (Duration)GetValue(SearchEventTimeDelayProperty); }
set { SetValue(SearchEventTimeDelayProperty, value); }
}
public bool IsMouseLeftButtonDown {
get { return (bool)GetValue(IsMouseLeftButtonDownProperty); }
private set { SetValue(IsMouseLeftButtonDownPropertyKey, value); }
}
public event RoutedEventHandler Search {
add { AddHandler(SearchEvent, value); }
remove { RemoveHandler(SearchEvent, value); }
}
}
}
| zzgaminginc-pointofssale | Lib/UIControls/SearchTextBox.cs | C# | gpl3 | 7,350 |
using System.Windows;
using System.Windows.Controls;
namespace UIControls
{
public sealed class BindablePasswordBox : Decorator
{
/// <summary>
/// The password dependency property.
/// </summary>
public static readonly DependencyProperty PasswordProperty;
private bool _isPreventCallback;
private readonly RoutedEventHandler _savedCallback;
/// <summary>
/// Static constructor to initialize the dependency properties.
/// </summary>
static BindablePasswordBox()
{
PasswordProperty = DependencyProperty.Register(
"Password",
typeof(string),
typeof(BindablePasswordBox),
new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnPasswordPropertyChanged)
);
}
/// <summary>
/// Saves the password changed callback and sets the child element to the password box.
/// </summary>
public BindablePasswordBox()
{
_savedCallback = HandlePasswordChanged;
var passwordBox = new PasswordBox();
passwordBox.PasswordChanged += _savedCallback;
Child = passwordBox;
}
/// <summary>
/// The password dependency property.
/// </summary>
public string Password
{
get { return GetValue(PasswordProperty) as string; }
set { SetValue(PasswordProperty, value); }
}
/// <summary>
/// Handles changes to the password dependency property.
/// </summary>
/// <param name="d">the dependency object</param>
/// <param name="eventArgs">the event args</param>
private static void OnPasswordPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs eventArgs)
{
var bindablePasswordBox = (BindablePasswordBox)d;
var passwordBox = (PasswordBox)bindablePasswordBox.Child;
if (bindablePasswordBox._isPreventCallback)
{
return;
}
passwordBox.PasswordChanged -= bindablePasswordBox._savedCallback;
passwordBox.Password = (eventArgs.NewValue != null) ? eventArgs.NewValue.ToString() : "";
passwordBox.PasswordChanged += bindablePasswordBox._savedCallback;
}
/// <summary>
/// Handles the password changed event.
/// </summary>
/// <param name="sender">the sender</param>
/// <param name="eventArgs">the event args</param>
private void HandlePasswordChanged(object sender, RoutedEventArgs eventArgs)
{
var passwordBox = (PasswordBox)sender;
_isPreventCallback = true;
Password = passwordBox.Password;
_isPreventCallback = false;
}
}
}
| zzgaminginc-pointofssale | Lib/UIControls/BindablePasswordBox.cs | C# | gpl3 | 2,994 |
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
namespace UIControls
{
public enum TickerDirection
{
East,
West
}
public class ContentTicker : ContentControl
{
Storyboard _ContentTickerStoryboard = null;
Canvas _ContentControl = null;
ContentPresenter _Content = null;
static ContentTicker()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ContentTicker), new FrameworkPropertyMetadata(typeof(ContentTicker)));
}
public ContentTicker()
{
this.Loaded += new RoutedEventHandler(ContentTicker_Loaded);
}
public void Start()
{
if (_ContentTickerStoryboard != null &&
!IsStarted)
{
UpdateAnimationDetails(_ContentControl.ActualWidth, _Content.ActualWidth);
_ContentTickerStoryboard.Begin(_ContentControl, true);
IsStarted = true;
}
}
public void Pause()
{
if (IsStarted &&
!IsPaused &&
_ContentTickerStoryboard != null)
{
_ContentTickerStoryboard.Pause(_ContentControl);
IsPaused = true;
}
}
public void Resume()
{
if (IsPaused &&
_ContentTickerStoryboard != null)
{
_ContentTickerStoryboard.Resume(_ContentControl);
IsPaused = false;
}
}
public void Stop()
{
if (_ContentTickerStoryboard != null &&
IsStarted)
{
_ContentTickerStoryboard.Stop(_ContentControl);
IsStarted = false;
}
}
public bool IsStarted { get; private set; }
public bool IsPaused { get; private set; }
public double Rate
{
get { return (double)GetValue(RateProperty); }
set { SetValue(RateProperty, value); }
}
public static readonly DependencyProperty RateProperty =
DependencyProperty.Register("Rate", typeof(double), typeof(ContentTicker), new UIPropertyMetadata(60.0));
public TickerDirection Direction
{
get { return (TickerDirection)GetValue(DirectionProperty); }
set { SetValue(DirectionProperty, value); }
}
public static readonly DependencyProperty DirectionProperty =
DependencyProperty.Register("Direction", typeof(TickerDirection), typeof(ContentTicker), new UIPropertyMetadata(TickerDirection.West));
void ContentTicker_Loaded(object sender, RoutedEventArgs e)
{
_ContentControl = GetTemplateChild("PART_ContentControl") as Canvas;
if (_ContentControl != null)
_ContentControl.SizeChanged += new SizeChangedEventHandler(_ContentControl_SizeChanged);
_Content = GetTemplateChild("PART_Content") as ContentPresenter;
if (_Content != null)
_Content.SizeChanged += new SizeChangedEventHandler(_Content_SizeChanged);
_ContentTickerStoryboard = GetTemplateChild("ContentTickerStoryboard") as Storyboard;
if (_ContentControl.ActualWidth == 0 && double.IsNaN(_ContentControl.Width))
_ContentControl.Width = _Content.ActualWidth;
if (_ContentControl.ActualHeight == 0 && double.IsNaN(_ContentControl.Height))
_ContentControl.Height = _Content.ActualHeight;
VerticallyAlignContent(_ContentControl.ActualHeight);
Start();
}
void _Content_SizeChanged(object sender, SizeChangedEventArgs e)
{
UpdateAnimationDetails(_ContentControl.ActualWidth, e.NewSize.Width);
}
void _ContentControl_SizeChanged(object sender, SizeChangedEventArgs e)
{
VerticallyAlignContent(e.NewSize.Height);
UpdateAnimationDetails(e.NewSize.Width, _Content.ActualWidth);
}
void VerticallyAlignContent(double height)
{
double contentHeight = _Content.ActualHeight;
switch (_Content.VerticalAlignment)
{
case System.Windows.VerticalAlignment.Top:
Canvas.SetTop(_Content, 0);
break;
case System.Windows.VerticalAlignment.Bottom:
if (height > contentHeight)
Canvas.SetTop(_Content, height - contentHeight);
break;
case System.Windows.VerticalAlignment.Center:
case System.Windows.VerticalAlignment.Stretch:
if (height > contentHeight)
Canvas.SetTop(_Content, (height - contentHeight) / 2);
break;
}
}
void UpdateAnimationDetails(double holderLength, double contentLength)
{
DoubleAnimation animation =
_ContentTickerStoryboard.Children.First() as DoubleAnimation;
if (animation != null)
{
bool start = false;
if (IsStarted)
{
Stop();
start = true;
}
double from = 0, to = 0, time = 0;
switch (Direction)
{
case TickerDirection.West:
from = holderLength;
to = -1 * contentLength;
time = from / Rate;
break;
case TickerDirection.East:
from = -1 * contentLength;
to = holderLength;
time = to / Rate;
break;
}
animation.From = from;
animation.To = to;
TimeSpan newDuration = TimeSpan.FromSeconds(time);
animation.Duration = new Duration(newDuration);
if (start)
{
TimeSpan? oldDuration = null;
if (animation.Duration.HasTimeSpan)
oldDuration = animation.Duration.TimeSpan;
TimeSpan? currentTime = _ContentTickerStoryboard.GetCurrentTime(_ContentControl);
int? iteration = _ContentTickerStoryboard.GetCurrentIteration(_ContentControl);
TimeSpan? offset =
TimeSpan.FromSeconds(
currentTime.HasValue ?
currentTime.Value.TotalSeconds % (oldDuration.HasValue ? oldDuration.Value.TotalSeconds : 1.0) :
0.0);
Start();
if (offset.HasValue &&
offset.Value != TimeSpan.Zero &&
offset.Value < newDuration)
_ContentTickerStoryboard.SeekAlignedToLastTick(_ContentControl, offset.Value, TimeSeekOrigin.BeginTime);
}
}
}
}
}
| zzgaminginc-pointofssale | Lib/UIControls/ContentTicker.cs | C# | gpl3 | 7,417 |
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
namespace UIControls
{
public class AnimatedTabControl : TabControl
{
public static readonly RoutedEvent SelectionChangingEvent = EventManager.RegisterRoutedEvent(
"SelectionChanging", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(AnimatedTabControl));
private DispatcherTimer _timer;
public AnimatedTabControl()
{
DefaultStyleKey = typeof(AnimatedTabControl);
}
public event RoutedEventHandler SelectionChanging
{
add { AddHandler(SelectionChangingEvent, value); }
remove { RemoveHandler(SelectionChangingEvent, value); }
}
protected override void OnSelectionChanged(SelectionChangedEventArgs e)
{
//if(e.RemovedItems.Count==0) return;
this.Dispatcher.BeginInvoke(
(Action)delegate
{
this.RaiseSelectionChangingEvent();
this.StopTimer();
this._timer = new DispatcherTimer { Interval = new TimeSpan(0, 0, 0, 0, 500) };
EventHandler handler = null;
handler = (sender, args) =>
{
this.StopTimer();
base.OnSelectionChanged(e);
};
this._timer.Tick += handler;
this._timer.Start();
});
}
// This method raises the Tap event
private void RaiseSelectionChangingEvent()
{
var args = new RoutedEventArgs(SelectionChangingEvent);
RaiseEvent(args);
}
private void StopTimer()
{
if (this._timer != null)
{
this._timer.Stop();
this._timer = null;
}
}
}
}
| zzgaminginc-pointofssale | Lib/UIControls/AnimatedTabControl.cs | C# | gpl3 | 2,028 |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("UIControls")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("UIControls")]
[assembly: AssemblyCopyright("Copyright © 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| zzgaminginc-pointofssale | Lib/UIControls/Properties/AssemblyInfo.cs | C# | gpl3 | 2,284 |
// Another Demo from Andy L. & MissedMemo.com
// Borrow whatever code seems useful - just don't try to hold
// me responsible for any ill effects. My demos sometimes use
// licensed images which CANNOT legally be copied and reused.
using System.Windows.Data;
using System.Windows;
namespace FlexButton
{
public class HighlightCornerRadiusConverter : IValueConverter
{
public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var corners = (CornerRadius)value;
//corners.BottomLeft = 0;
//corners.BottomRight = 0;
return corners;
}
public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new System.NotImplementedException();
}
}
}
| zzgaminginc-pointofssale | Lib/FlexButton/convertHighlightCornerRadius.cs | C# | gpl3 | 931 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
namespace FlexButton
{
public class ColorHSL
{
private short _h;
public short H
{
get { return _h; }
set
{
_h = value;
if (_h < 0) _h = 0;
}
}
private short _s;
public short S
{
get { return _s; }
set
{
_s = value;
if (_s < 0) _s = 0;
}
}
private short _l;
public short L
{
get { return _l; }
set
{
_l = value;
if (_l > 230) _l = 230;
if (_l < 0) _l = 0;
}
}
}
public static class ColorTools
{
public static ColorHSL RGBtoHSL(Color colorRGB)
{
var hsl = new ColorHSL();
float r, g, b, h, s, l; //this function works with floats between 0 and 1
r = colorRGB.R / 256.0f;
g = colorRGB.G / 256.0f;
b = colorRGB.B / 256.0f;
float maxColor = Math.Max(r, Math.Max(g, b));
float minColor = Math.Min(r, Math.Min(g, b));
//R == G == B, so it's a shade of gray
if (r == g && r == b)
{
h = 0.0f; //it doesn't matter what value it has
s = 0.0f;
l = r; //doesn't matter if you pick r, g, or b
}
else
{
l = (minColor + maxColor) / 2;
if (l < 0.5) s = (maxColor - minColor) / (maxColor + minColor);
else s = (maxColor - minColor) / (2.0f - maxColor - minColor);
if (r == maxColor) h = (g - b) / (maxColor - minColor);
else if (g == maxColor) h = 2.0f + (b - r) / (maxColor - minColor);
else h = 4.0f + (r - g) / (maxColor - minColor);
h /= 6; //to bring it to a number between 0 and 1
if (h < 0) h++;
}
hsl.H = (short)(h * 255);
hsl.L = (short)(l * 255);
hsl.S = (short)(s * 255);
return hsl;
}
public static Color HSLtoRGB(ColorHSL colorHSL)
{
double r, g, b; //this function works with floats between 0 and 1
var h = colorHSL.H / 256.0;
var s = colorHSL.S / 256.0;
var l = colorHSL.L / 256.0;
//If saturation is 0, the color is a shade of gray
if (s == 0)
{
r = g = b = l;
}
else
{
//Set the temporary values
double temp2;
if (l < 0.5)
{
temp2 = l * (1 + s);
}
else
{
temp2 = (l + s) - (l * s);
}
double temp1 = 2 * l - temp2;
double tempr = h + 1.0 / 3.0;
if (tempr > 1)
{
tempr--;
}
double tempg = h;
double tempb = h - 1.0 / 3.0;
if (tempb < 0)
tempb++;
//Red
if (tempr < 1.0 / 6.0) r = temp1 + (temp2 - temp1) * 6.0 * tempr;
else if (tempr < 0.5) r = temp2;
else if (tempr < 2.0 / 3.0) r = temp1 + (temp2 - temp1) * ((2.0 / 3.0) - tempr) * 6.0;
else r = temp1;
//Green
if (tempg < 1.0 / 6.0) g = temp1 + (temp2 - temp1) * 6.0 * tempg;
else if (tempg < 0.5) g = temp2;
else if (tempg < 2.0 / 3.0) g = temp1 + (temp2 - temp1) * ((2.0 / 3.0) - tempg) * 6.0;
else g = temp1;
//Blue
if (tempb < 1.0 / 6.0) b = temp1 + (temp2 - temp1) * 6.0 * tempb;
else if (tempb < 0.5) b = temp2;
else if (tempb < 2.0 / 3.0) b = temp1 + (temp2 - temp1) * ((2.0 / 3.0) - tempb) * 6.0;
else b = temp1;
}
return Color.FromRgb(Convert.ToByte(r * 255), Convert.ToByte(g * 255), Convert.ToByte(b * 255));
}
}
}
| zzgaminginc-pointofssale | Lib/FlexButton/ColorHSL.cs | C# | gpl3 | 4,551 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
namespace FlexButton
{
public class ButtonTextTemplateSelector : DataTemplateSelector
{
public DataTemplate DefaultTemplate { get; set; }
public DataTemplate StringTemplate { get; set; }
public override DataTemplate SelectTemplate(object item,
DependencyObject container)
{
if (item is String) return StringTemplate;
return null;
}
}
}
| zzgaminginc-pointofssale | Lib/FlexButton/ButtonTextTemplateSelector.cs | C# | gpl3 | 588 |
// Another Demo from Andy L. & MissedMemo.com
// Borrow whatever code seems useful - just don't try to hold
// me responsible for any ill effects. My demos sometimes use
// licensed images which CANNOT legally be copied and reused.
using System;
using System.Windows.Data;
using System.Windows.Media;
namespace FlexButton
{
public class BrightnessToColorConverter : IValueConverter
{
public object Convert( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
{
var brightness = (byte)value;
return Color.FromArgb( brightness, 255, 255, 255 );
}
public object ConvertBack( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
{
throw new NotImplementedException();
}
}
}
| zzgaminginc-pointofssale | Lib/FlexButton/convertBrightnessToColorWithAlpha.cs | C# | gpl3 | 885 |
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
namespace FlexButton
{
/// <summary>
/// Follow steps 1a or 1b and then 2 to use this custom control in a XAML file.
///
/// Step 1a) Using this custom control in a XAML file that exists in the current project.
/// Add this XmlNamespace attribute to the root element of the markup file where it is
/// to be used:
///
/// xmlns:MyNamespace="clr-namespace:FlexButton"
///
///
/// Step 1b) Using this custom control in a XAML file that exists in a different project.
/// Add this XmlNamespace attribute to the root element of the markup file where it is
/// to be used:
///
/// xmlns:MyNamespace="clr-namespace:FlexButton;assembly=FlexButton"
///
/// You will also need to add a project reference from the project where the XAML file lives
/// to this project and Rebuild to avoid compilation errors:
///
/// Right click on the target project in the Solution Explorer and
/// "Add Reference"->"Projects"->[Select this project]
///
///
/// Step 2)
/// Go ahead and use your control in the XAML file.
///
/// <MyNamespace:CustomControl1/>
///
/// </summary>
public class FlexButton : ToggleButton
{
public enum Highlight { Diffuse, Elliptical, Image }
public static readonly DependencyProperty CornerRadiusProperty =
Border.CornerRadiusProperty.AddOwner(typeof(FlexButton));
public static readonly DependencyProperty OuterBorderBrushProperty =
DependencyProperty.Register("OuterBorderBrush", typeof(Brush), typeof(FlexButton));
public static readonly DependencyProperty OuterBorderThicknessProperty =
DependencyProperty.Register("OuterBorderThickness", typeof(Thickness), typeof(FlexButton));
public static readonly DependencyProperty InnerBorderBrushProperty =
DependencyProperty.Register("InnerBorderBrush", typeof(Brush), typeof(FlexButton));
public static readonly DependencyProperty InnerBorderThicknessProperty =
DependencyProperty.Register("InnerBorderThickness", typeof(Thickness), typeof(FlexButton));
public static readonly DependencyProperty GlowColorProperty =
DependencyProperty.Register("GlowColor", typeof(SolidColorBrush), typeof(FlexButton));
public static readonly DependencyProperty ButtonColorProperty =
DependencyProperty.Register("ButtonColor", typeof(SolidColorBrush), typeof(FlexButton),
new FrameworkPropertyMetadata(new PropertyChangedCallback(OnButtonColorChanged)));
public static readonly DependencyProperty HighlightAppearanceProperty =
DependencyProperty.Register("HighlightAppearance", typeof(ControlTemplate), typeof(FlexButton));
public static readonly DependencyProperty HighlightMarginProperty =
DependencyProperty.Register("HighlightMargin", typeof(Thickness), typeof(FlexButton));
public static readonly DependencyProperty HighlightBrightnessProperty =
DependencyProperty.Register("HighlightBrightness", typeof(byte), typeof(FlexButton));
public static readonly DependencyProperty ButtonImageProperty =
DependencyProperty.Register("ButtonImage", typeof(ImageSource), typeof(FlexButton));
public static readonly DependencyProperty IsImageOnlyProperty =
DependencyProperty.Register("IsImageOnly", typeof(bool), typeof(FlexButton));
#region Properties...
public Visibility IsHeaderVisible { get { return IsImageOnly ? Visibility.Visible : Visibility.Collapsed; } }
public Visibility IsHeaderInvisible { get { return IsImageOnly ? Visibility.Collapsed : Visibility.Visible; } }
public bool IsImageOnly
{
get { return (bool)GetValue(IsImageOnlyProperty); }
set { SetValue(IsImageOnlyProperty, value); }
}
public ImageSource ButtonImage
{
get { return (ImageSource)GetValue(ButtonImageProperty); }
set { SetValue(ButtonImageProperty, value); }
}
public Brush GlowColor
{
get { return (SolidColorBrush)GetValue(GlowColorProperty); }
set { SetValue(GlowColorProperty, value); }
}
public Brush ButtonColor
{
get { return (SolidColorBrush)GetValue(ButtonColorProperty); }
set { SetValue(ButtonColorProperty, value); }
}
public CornerRadius CornerRadius
{
get { return (CornerRadius)GetValue(CornerRadiusProperty); }
set { SetValue(CornerRadiusProperty, value); }
}
public Brush OuterBorderBrush
{
get { return (Brush)GetValue(OuterBorderBrushProperty); }
set { SetValue(OuterBorderBrushProperty, value); }
}
public Thickness OuterBorderThickness
{
get { return (Thickness)GetValue(OuterBorderThicknessProperty); }
set { SetValue(OuterBorderThicknessProperty, value); }
}
public Brush InnerBorderBrush
{
get { return (Brush)GetValue(InnerBorderBrushProperty); }
set { SetValue(InnerBorderBrushProperty, value); }
}
public Thickness InnerBorderThickness
{
get { return (Thickness)GetValue(InnerBorderThicknessProperty); }
set { SetValue(InnerBorderThicknessProperty, value); }
}
// Force clients to pass enum value to HighlightStyle by hiding this accessor
internal ControlTemplate HighlightAppearance
{
get { return (ControlTemplate)GetValue(HighlightAppearanceProperty); }
set { SetValue(HighlightAppearanceProperty, value); }
}
public Thickness HighlightMargin
{
get { return (Thickness)GetValue(HighlightMarginProperty); }
set { SetValue(HighlightMarginProperty, value); }
}
public byte HighlightBrightness
{
get { return (byte)GetValue(HighlightBrightnessProperty); }
set { SetValue(HighlightBrightnessProperty, value); }
}
#endregion (Properties)
static FlexButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(FlexButton), new FrameworkPropertyMetadata(typeof(FlexButton)));
}
public FlexButton()
{
HighlightMargin = new Thickness(0);
HighlightBrightness = 100;
GlowColor = Brushes.WhiteSmoke;
OuterBorderBrush = Brushes.Gray;
InnerBorderBrush = new LinearGradientBrush(Colors.White, Colors.LightGray, 90);
InnerBorderThickness = new Thickness(1);
CornerRadius = new CornerRadius(3);
UpdateButtonColor(this, Brushes.Gainsboro);
Foreground = Brushes.Black;
IsEnabledChanged += FlexButtonIsEnabledChanged;
}
void FlexButtonIsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
{
SolidColorBrush brush = ButtonColor != null ? (SolidColorBrush)ButtonColor : Brushes.Gainsboro;
UpdateForeground(brush, this);
}
private static void OnButtonColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue != null)
UpdateButtonColor((FlexButton)d, (SolidColorBrush)e.NewValue);
else UpdateButtonColor((FlexButton)d, Brushes.Gainsboro);
}
private static void UpdateButtonColor(FlexButton item, SolidColorBrush color)
{
var btn = item;
var fColor = color;
var gColor = new SolidColorBrush(fColor.Color.Lerp(Colors.White, 0.75f));
btn.InnerBorderBrush = new LinearGradientBrush(Colors.White, gColor.Color, 90);
UpdateForeground(fColor, btn);
btn.Background = fColor;
btn.GlowColor = (gColor);
}
private static int Brightness(Color c)
{
return (int)Math.Sqrt(
c.R * c.R * .241 +
c.G * c.G * .691 +
c.B * c.B * .068);
}
private static void UpdateForeground(SolidColorBrush fColor, FlexButton btn)
{
if (fColor == null) return;
btn.Foreground = btn.IsEnabled
? new SolidColorBrush(Brightness(fColor.Color) < 150 ? Colors.White : Colors.Black)
: new SolidColorBrush(fColor.Color.Lerp(Colors.Black, 0.25f));
}
}
}
| zzgaminginc-pointofssale | Lib/FlexButton/FlexButton.cs | C# | gpl3 | 8,972 |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FlexButton")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FlexButton")]
[assembly: AssemblyCopyright("Copyright © 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| zzgaminginc-pointofssale | Lib/FlexButton/Properties/AssemblyInfo.cs | C# | gpl3 | 2,284 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
namespace FlexButton
{
public static class FlexButtonExtensions
{
public static float Lerp(this float start, float end, float amount)
{
float difference = end - start;
float adjusted = difference * amount;
return start + adjusted;
}
public static Color Lerp(this Color colour, Color to, float amount)
{
// start colours as lerp-able floats
float sr = colour.R, sg = colour.G, sb = colour.B;
// end colours as lerp-able floats
float er = to.R, eg = to.G, eb = to.B;
// lerp the colours to get the difference
byte r = (byte)sr.Lerp(er, amount),
g = (byte)sg.Lerp(eg, amount),
b = (byte)sb.Lerp(eb, amount);
// return the new colour
return Color.FromArgb(colour.A, r, g, b);
}
}
}
| zzgaminginc-pointofssale | Lib/FlexButton/FlexButtonExtensions.cs | C# | gpl3 | 1,061 |
// Another Demo from Andy L. & MissedMemo.com
// Borrow whatever code seems useful - just don't try to hold
// me responsible for any ill effects. My demos sometimes use
// licensed images which CANNOT legally be copied and reused.
using System;
using System.Windows.Data;
using System.Windows.Media;
namespace FlexButton
{
public class ColorToAlphaColorConverter : IValueConverter
{
public object Convert( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
{
var brush = (SolidColorBrush)value;
if( brush != null )
{
var color = brush.Color;
color.A = byte.Parse( parameter.ToString() );
return color;
}
return Colors.Black; // make error obvious
}
public object ConvertBack( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
{
throw new NotImplementedException();
}
}
}
| zzgaminginc-pointofssale | Lib/FlexButton/convertColorToColorWithAlpha.cs | C# | gpl3 | 1,109 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DataGridFilterLibrary.Support
{
/// <summary>
/// Code from: http://www.ageektrapped.com/blog/the-missing-net-7-displaying-enums-in-wpf/
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
public sealed class DisplayStringAttribute : Attribute
{
private readonly string value;
public string Value
{
get { return value; }
}
public string ResourceKey { get; set; }
public DisplayStringAttribute(string v)
{
this.value = v;
}
public DisplayStringAttribute()
{
}
}
}
| zzgaminginc-pointofssale | Lib/DataGridFilterLibrary/Support/DisplayStringAttribute.cs | C# | gpl3 | 741 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Globalization;
namespace DataGridFilterLibrary.Support
{
public class MyOppositeBooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(bool)value)
{
return System.Windows.Visibility.Visible;
}
else
{
return System.Windows.Visibility.Collapsed;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
System.Windows.Visibility visibility = (System.Windows.Visibility)value;
return visibility == System.Windows.Visibility.Visible ? true : false;
}
}
}
| zzgaminginc-pointofssale | Lib/DataGridFilterLibrary/Support/MyOppositeBooleanToVisibilityConverter.cs | C# | gpl3 | 941 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Timers;
using System.Windows;
namespace DataGridFilterLibrary.Support
{
/// <summary>
/// WPF port of windows forms version: http://www.codeproject.com/KB/miscctrl/CustomTextBox.aspx
/// </summary>
public class DelayTextBox : TextBox
{
#region private globals
private Timer DelayTimer; // used for the delay
private bool TimerElapsed = false; // if true OnTextChanged is fired.
private bool KeysPressed = false; // makes event fire immediately if it wasn't a keypress
private int DELAY_TIME = 250;//for now best empiric value
public static readonly DependencyProperty DelayTimeProperty =
DependencyProperty.Register("DelayTime", typeof(int), typeof(DelayTextBox));
#endregion
#region ctor
public DelayTextBox()
: base()
{
// Initialize Timer
DelayTimer = new Timer(DELAY_TIME);
DelayTimer.Elapsed += new ElapsedEventHandler(DelayTimer_Elapsed);
previousTextChangedEventArgs = null;
AddHandler(TextBox.PreviewKeyDownEvent, new System.Windows.Input.KeyEventHandler(DelayTextBox_PreviewKeyDown));
PreviousTextValue = String.Empty;
}
void DelayTextBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (!DelayTimer.Enabled)
DelayTimer.Enabled = true;
else
{
DelayTimer.Enabled = false;
DelayTimer.Enabled = true;
}
KeysPressed = true;
}
#endregion
#region event handlers
void DelayTimer_Elapsed(object sender, ElapsedEventArgs e)
{
DelayTimer.Enabled = false;// stop timer.
TimerElapsed = true;// set timer elapsed to true, so the OnTextChange knows to fire
this.Dispatcher.Invoke(new DelayOverHandler(DelayOver), null);// use invoke to get back on the UI thread.
}
#endregion
#region overrides
private TextChangedEventArgs previousTextChangedEventArgs;
public string PreviousTextValue { get; private set; }
protected override void OnTextChanged(TextChangedEventArgs e)
{
// if the timer elapsed or text was changed by something besides a keystroke
// fire base.OnTextChanged
if (TimerElapsed || !KeysPressed)
{
TimerElapsed = false;
KeysPressed = false;
base.OnTextChanged(e);
System.Windows.Data.BindingExpression be = this.GetBindingExpression(TextBox.TextProperty);
if (be != null && be.Status==System.Windows.Data.BindingStatus.Active) be.UpdateSource();
PreviousTextValue = Text;
}
previousTextChangedEventArgs = e;
}
#endregion
#region delegates
public delegate void DelayOverHandler();
#endregion
#region private helpers
private void DelayOver()
{
if (previousTextChangedEventArgs != null)
OnTextChanged(previousTextChangedEventArgs);
}
#endregion
}
}
| zzgaminginc-pointofssale | Lib/DataGridFilterLibrary/Support/DelayTextBox.cs | C# | gpl3 | 3,495 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DataGridFilterLibrary.Support
{
public enum FilterOperator
{
Undefined,
LessThan,
LessThanOrEqual,
GreaterThan,
GreaterThanOrEqual,
Equals,
Like,
Between
}
}
| zzgaminginc-pointofssale | Lib/DataGridFilterLibrary/Support/FilterOperator.cs | C# | gpl3 | 353 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
namespace DataGridFilterLibrary.Support
{
public class ComboBoxToQueryStringConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value != null && value.ToString() == String.Empty ? null : value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value;
}
#endregion
}
}
| zzgaminginc-pointofssale | Lib/DataGridFilterLibrary/Support/ComboBoxToQueryStringConverter.cs | C# | gpl3 | 723 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Globalization;
namespace DataGridFilterLibrary.Support
{
public class ClearFilterButtonVisibilityConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if ((bool)values[0] && (bool)values[1])
{
return System.Windows.Visibility.Visible;
}
else
{
return System.Windows.Visibility.Collapsed;
}
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| zzgaminginc-pointofssale | Lib/DataGridFilterLibrary/Support/ClearFilterButtonVisibilityConverter.cs | C# | gpl3 | 852 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
namespace DataGridFilterLibrary.Support
{
public class DatePickerToQueryStringConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
object convertedValue;
if (value != null && value.ToString() == String.Empty)
{
convertedValue = null;
}
else
{
DateTime dateTime;
if (DateTime.TryParse(
value.ToString(),
culture.DateTimeFormat,
System.Globalization.DateTimeStyles.None,
out dateTime))
{
convertedValue = dateTime;
}
else
{
convertedValue = null;
}
}
return convertedValue;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value;
}
#endregion
}
}
| zzgaminginc-pointofssale | Lib/DataGridFilterLibrary/Support/DatePickerToQueryStringConverter.cs | C# | gpl3 | 1,352 |
//Copyright (C) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
namespace System.Linq.Dynamic
{
public static class DynamicQueryable
{
public static IQueryable<T> Where<T>(this IQueryable<T> source, string predicate, params object[] values)
{
return (IQueryable<T>)Where((IQueryable)source, predicate, values);
}
public static IQueryable Where(this IQueryable source, string predicate, params object[] values)
{
if (source == null) throw new ArgumentNullException("source");
if (predicate == null) throw new ArgumentNullException("predicate");
LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType, typeof(bool), predicate, values);
return source.Provider.CreateQuery(
Expression.Call(
typeof(Queryable), "Where",
new Type[] { source.ElementType },
source.Expression, Expression.Quote(lambda)));
}
public static IQueryable Select(this IQueryable source, string selector, params object[] values)
{
if (source == null) throw new ArgumentNullException("source");
if (selector == null) throw new ArgumentNullException("selector");
LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType, null, selector, values);
return source.Provider.CreateQuery(
Expression.Call(
typeof(Queryable), "Select",
new Type[] { source.ElementType, lambda.Body.Type },
source.Expression, Expression.Quote(lambda)));
}
public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string ordering, params object[] values)
{
return (IQueryable<T>)OrderBy((IQueryable)source, ordering, values);
}
public static IQueryable OrderBy(this IQueryable source, string ordering, params object[] values)
{
if (source == null) throw new ArgumentNullException("source");
if (ordering == null) throw new ArgumentNullException("ordering");
ParameterExpression[] parameters = new ParameterExpression[] {
Expression.Parameter(source.ElementType, "") };
ExpressionParser parser = new ExpressionParser(parameters, ordering, values);
IEnumerable<DynamicOrdering> orderings = parser.ParseOrdering();
Expression queryExpr = source.Expression;
string methodAsc = "OrderBy";
string methodDesc = "OrderByDescending";
foreach (DynamicOrdering o in orderings)
{
queryExpr = Expression.Call(
typeof(Queryable), o.Ascending ? methodAsc : methodDesc,
new Type[] { source.ElementType, o.Selector.Type },
queryExpr, Expression.Quote(Expression.Lambda(o.Selector, parameters)));
methodAsc = "ThenBy";
methodDesc = "ThenByDescending";
}
return source.Provider.CreateQuery(queryExpr);
}
public static IQueryable Take(this IQueryable source, int count)
{
if (source == null) throw new ArgumentNullException("source");
return source.Provider.CreateQuery(
Expression.Call(
typeof(Queryable), "Take",
new Type[] { source.ElementType },
source.Expression, Expression.Constant(count)));
}
public static IQueryable Skip(this IQueryable source, int count)
{
if (source == null) throw new ArgumentNullException("source");
return source.Provider.CreateQuery(
Expression.Call(
typeof(Queryable), "Skip",
new Type[] { source.ElementType },
source.Expression, Expression.Constant(count)));
}
public static IQueryable GroupBy(this IQueryable source, string keySelector, string elementSelector, params object[] values)
{
if (source == null) throw new ArgumentNullException("source");
if (keySelector == null) throw new ArgumentNullException("keySelector");
if (elementSelector == null) throw new ArgumentNullException("elementSelector");
LambdaExpression keyLambda = DynamicExpression.ParseLambda(source.ElementType, null, keySelector, values);
LambdaExpression elementLambda = DynamicExpression.ParseLambda(source.ElementType, null, elementSelector, values);
return source.Provider.CreateQuery(
Expression.Call(
typeof(Queryable), "GroupBy",
new Type[] { source.ElementType, keyLambda.Body.Type, elementLambda.Body.Type },
source.Expression, Expression.Quote(keyLambda), Expression.Quote(elementLambda)));
}
public static bool Any(this IQueryable source)
{
if (source == null) throw new ArgumentNullException("source");
return (bool)source.Provider.Execute(
Expression.Call(
typeof(Queryable), "Any",
new Type[] { source.ElementType }, source.Expression));
}
public static int Count(this IQueryable source)
{
if (source == null) throw new ArgumentNullException("source");
return (int)source.Provider.Execute(
Expression.Call(
typeof(Queryable), "Count",
new Type[] { source.ElementType }, source.Expression));
}
}
public abstract class DynamicClass
{
public override string ToString()
{
PropertyInfo[] props = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
StringBuilder sb = new StringBuilder();
sb.Append("{");
for (int i = 0; i < props.Length; i++)
{
if (i > 0) sb.Append(", ");
sb.Append(props[i].Name);
sb.Append("=");
sb.Append(props[i].GetValue(this, null));
}
sb.Append("}");
return sb.ToString();
}
}
public class DynamicProperty
{
string name;
Type type;
public DynamicProperty(string name, Type type)
{
if (name == null) throw new ArgumentNullException("name");
if (type == null) throw new ArgumentNullException("type");
this.name = name;
this.type = type;
}
public string Name
{
get { return name; }
}
public Type Type
{
get { return type; }
}
}
public static class DynamicExpression
{
public static Expression Parse(Type resultType, string expression, params object[] values)
{
ExpressionParser parser = new ExpressionParser(null, expression, values);
return parser.Parse(resultType);
}
public static LambdaExpression ParseLambda(Type itType, Type resultType, string expression, params object[] values)
{
return ParseLambda(new ParameterExpression[] { Expression.Parameter(itType, "") }, resultType, expression, values);
}
public static LambdaExpression ParseLambda(ParameterExpression[] parameters, Type resultType, string expression, params object[] values)
{
ExpressionParser parser = new ExpressionParser(parameters, expression, values);
return Expression.Lambda(parser.Parse(resultType), parameters);
}
public static Expression<Func<T, S>> ParseLambda<T, S>(string expression, params object[] values)
{
return (Expression<Func<T, S>>)ParseLambda(typeof(T), typeof(S), expression, values);
}
public static Type CreateClass(params DynamicProperty[] properties)
{
return ClassFactory.Instance.GetDynamicClass(properties);
}
public static Type CreateClass(IEnumerable<DynamicProperty> properties)
{
return ClassFactory.Instance.GetDynamicClass(properties);
}
}
internal class DynamicOrdering
{
public Expression Selector;
public bool Ascending;
}
internal class Signature : IEquatable<Signature>
{
public DynamicProperty[] properties;
public int hashCode;
public Signature(IEnumerable<DynamicProperty> properties)
{
this.properties = properties.ToArray();
hashCode = 0;
foreach (DynamicProperty p in properties)
{
hashCode ^= p.Name.GetHashCode() ^ p.Type.GetHashCode();
}
}
public override int GetHashCode()
{
return hashCode;
}
public override bool Equals(object obj)
{
return obj is Signature ? Equals((Signature)obj) : false;
}
public bool Equals(Signature other)
{
if (properties.Length != other.properties.Length) return false;
for (int i = 0; i < properties.Length; i++)
{
if (properties[i].Name != other.properties[i].Name ||
properties[i].Type != other.properties[i].Type) return false;
}
return true;
}
}
internal class ClassFactory
{
public static readonly ClassFactory Instance = new ClassFactory();
static ClassFactory() { } // Trigger lazy initialization of static fields
ModuleBuilder module;
Dictionary<Signature, Type> classes;
int classCount;
ReaderWriterLock rwLock;
private ClassFactory()
{
AssemblyName name = new AssemblyName("DynamicClasses");
AssemblyBuilder assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
#if ENABLE_LINQ_PARTIAL_TRUST
new ReflectionPermission(PermissionState.Unrestricted).Assert();
#endif
try
{
module = assembly.DefineDynamicModule("Module");
}
finally
{
#if ENABLE_LINQ_PARTIAL_TRUST
PermissionSet.RevertAssert();
#endif
}
classes = new Dictionary<Signature, Type>();
rwLock = new ReaderWriterLock();
}
public Type GetDynamicClass(IEnumerable<DynamicProperty> properties)
{
rwLock.AcquireReaderLock(Timeout.Infinite);
try
{
Signature signature = new Signature(properties);
Type type;
if (!classes.TryGetValue(signature, out type))
{
type = CreateDynamicClass(signature.properties);
classes.Add(signature, type);
}
return type;
}
finally
{
rwLock.ReleaseReaderLock();
}
}
Type CreateDynamicClass(DynamicProperty[] properties)
{
LockCookie cookie = rwLock.UpgradeToWriterLock(Timeout.Infinite);
try
{
string typeName = "DynamicClass" + (classCount + 1);
#if ENABLE_LINQ_PARTIAL_TRUST
new ReflectionPermission(PermissionState.Unrestricted).Assert();
#endif
try
{
TypeBuilder tb = this.module.DefineType(typeName, TypeAttributes.Class |
TypeAttributes.Public, typeof(DynamicClass));
FieldInfo[] fields = GenerateProperties(tb, properties);
GenerateEquals(tb, fields);
GenerateGetHashCode(tb, fields);
Type result = tb.CreateType();
classCount++;
return result;
}
finally
{
#if ENABLE_LINQ_PARTIAL_TRUST
PermissionSet.RevertAssert();
#endif
}
}
finally
{
rwLock.DowngradeFromWriterLock(ref cookie);
}
}
FieldInfo[] GenerateProperties(TypeBuilder tb, DynamicProperty[] properties)
{
FieldInfo[] fields = new FieldBuilder[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
DynamicProperty dp = properties[i];
FieldBuilder fb = tb.DefineField("_" + dp.Name, dp.Type, FieldAttributes.Private);
PropertyBuilder pb = tb.DefineProperty(dp.Name, PropertyAttributes.HasDefault, dp.Type, null);
MethodBuilder mbGet = tb.DefineMethod("get_" + dp.Name,
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig,
dp.Type, Type.EmptyTypes);
ILGenerator genGet = mbGet.GetILGenerator();
genGet.Emit(OpCodes.Ldarg_0);
genGet.Emit(OpCodes.Ldfld, fb);
genGet.Emit(OpCodes.Ret);
MethodBuilder mbSet = tb.DefineMethod("set_" + dp.Name,
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig,
null, new Type[] { dp.Type });
ILGenerator genSet = mbSet.GetILGenerator();
genSet.Emit(OpCodes.Ldarg_0);
genSet.Emit(OpCodes.Ldarg_1);
genSet.Emit(OpCodes.Stfld, fb);
genSet.Emit(OpCodes.Ret);
pb.SetGetMethod(mbGet);
pb.SetSetMethod(mbSet);
fields[i] = fb;
}
return fields;
}
void GenerateEquals(TypeBuilder tb, FieldInfo[] fields)
{
MethodBuilder mb = tb.DefineMethod("Equals",
MethodAttributes.Public | MethodAttributes.ReuseSlot |
MethodAttributes.Virtual | MethodAttributes.HideBySig,
typeof(bool), new Type[] { typeof(object) });
ILGenerator gen = mb.GetILGenerator();
LocalBuilder other = gen.DeclareLocal(tb);
Label next = gen.DefineLabel();
gen.Emit(OpCodes.Ldarg_1);
gen.Emit(OpCodes.Isinst, tb);
gen.Emit(OpCodes.Stloc, other);
gen.Emit(OpCodes.Ldloc, other);
gen.Emit(OpCodes.Brtrue_S, next);
gen.Emit(OpCodes.Ldc_I4_0);
gen.Emit(OpCodes.Ret);
gen.MarkLabel(next);
foreach (FieldInfo field in fields)
{
Type ft = field.FieldType;
Type ct = typeof(EqualityComparer<>).MakeGenericType(ft);
next = gen.DefineLabel();
gen.EmitCall(OpCodes.Call, ct.GetMethod("get_Default"), null);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldfld, field);
gen.Emit(OpCodes.Ldloc, other);
gen.Emit(OpCodes.Ldfld, field);
gen.EmitCall(OpCodes.Callvirt, ct.GetMethod("Equals", new Type[] { ft, ft }), null);
gen.Emit(OpCodes.Brtrue_S, next);
gen.Emit(OpCodes.Ldc_I4_0);
gen.Emit(OpCodes.Ret);
gen.MarkLabel(next);
}
gen.Emit(OpCodes.Ldc_I4_1);
gen.Emit(OpCodes.Ret);
}
void GenerateGetHashCode(TypeBuilder tb, FieldInfo[] fields)
{
MethodBuilder mb = tb.DefineMethod("GetHashCode",
MethodAttributes.Public | MethodAttributes.ReuseSlot |
MethodAttributes.Virtual | MethodAttributes.HideBySig,
typeof(int), Type.EmptyTypes);
ILGenerator gen = mb.GetILGenerator();
gen.Emit(OpCodes.Ldc_I4_0);
foreach (FieldInfo field in fields)
{
Type ft = field.FieldType;
Type ct = typeof(EqualityComparer<>).MakeGenericType(ft);
gen.EmitCall(OpCodes.Call, ct.GetMethod("get_Default"), null);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldfld, field);
gen.EmitCall(OpCodes.Callvirt, ct.GetMethod("GetHashCode", new Type[] { ft }), null);
gen.Emit(OpCodes.Xor);
}
gen.Emit(OpCodes.Ret);
}
}
public sealed class ParseException : Exception
{
int position;
public ParseException(string message, int position)
: base(message)
{
this.position = position;
}
public int Position
{
get { return position; }
}
public override string ToString()
{
return string.Format(Res.ParseExceptionFormat, Message, position);
}
}
internal class ExpressionParser
{
struct Token
{
public TokenId id;
public string text;
public int pos;
}
enum TokenId
{
Unknown,
End,
Identifier,
StringLiteral,
IntegerLiteral,
RealLiteral,
Exclamation,
Percent,
Amphersand,
OpenParen,
CloseParen,
Asterisk,
Plus,
Comma,
Minus,
Dot,
Slash,
Colon,
LessThan,
Equal,
GreaterThan,
Question,
OpenBracket,
CloseBracket,
Bar,
ExclamationEqual,
DoubleAmphersand,
LessThanEqual,
LessGreater,
DoubleEqual,
GreaterThanEqual,
DoubleBar
}
interface ILogicalSignatures
{
void F(bool x, bool y);
void F(bool? x, bool? y);
}
interface IArithmeticSignatures
{
void F(int x, int y);
void F(uint x, uint y);
void F(long x, long y);
void F(ulong x, ulong y);
void F(float x, float y);
void F(double x, double y);
void F(decimal x, decimal y);
void F(int? x, int? y);
void F(uint? x, uint? y);
void F(long? x, long? y);
void F(ulong? x, ulong? y);
void F(float? x, float? y);
void F(double? x, double? y);
void F(decimal? x, decimal? y);
}
interface IRelationalSignatures : IArithmeticSignatures
{
void F(string x, string y);
void F(char x, char y);
void F(DateTime x, DateTime y);
void F(TimeSpan x, TimeSpan y);
void F(char? x, char? y);
void F(DateTime? x, DateTime? y);
void F(TimeSpan? x, TimeSpan? y);
}
interface IEqualitySignatures : IRelationalSignatures
{
void F(bool x, bool y);
void F(bool? x, bool? y);
}
interface IAddSignatures : IArithmeticSignatures
{
void F(DateTime x, TimeSpan y);
void F(TimeSpan x, TimeSpan y);
void F(DateTime? x, TimeSpan? y);
void F(TimeSpan? x, TimeSpan? y);
}
interface ISubtractSignatures : IAddSignatures
{
void F(DateTime x, DateTime y);
void F(DateTime? x, DateTime? y);
}
interface INegationSignatures
{
void F(int x);
void F(long x);
void F(float x);
void F(double x);
void F(decimal x);
void F(int? x);
void F(long? x);
void F(float? x);
void F(double? x);
void F(decimal? x);
}
interface INotSignatures
{
void F(bool x);
void F(bool? x);
}
interface IEnumerableSignatures
{
void Where(bool predicate);
void Any();
void Any(bool predicate);
void All(bool predicate);
void Count();
void Count(bool predicate);
void Min(object selector);
void Max(object selector);
void Sum(int selector);
void Sum(int? selector);
void Sum(long selector);
void Sum(long? selector);
void Sum(float selector);
void Sum(float? selector);
void Sum(double selector);
void Sum(double? selector);
void Sum(decimal selector);
void Sum(decimal? selector);
void Average(int selector);
void Average(int? selector);
void Average(long selector);
void Average(long? selector);
void Average(float selector);
void Average(float? selector);
void Average(double selector);
void Average(double? selector);
void Average(decimal selector);
void Average(decimal? selector);
}
static readonly Type[] predefinedTypes = {
typeof(Object),
typeof(Boolean),
typeof(Char),
typeof(String),
typeof(SByte),
typeof(Byte),
typeof(Int16),
typeof(UInt16),
typeof(Int32),
typeof(UInt32),
typeof(Int64),
typeof(UInt64),
typeof(Single),
typeof(Double),
typeof(Decimal),
typeof(DateTime),
typeof(TimeSpan),
typeof(Guid),
typeof(Math),
typeof(Convert)
};
static readonly Expression trueLiteral = Expression.Constant(true);
static readonly Expression falseLiteral = Expression.Constant(false);
static readonly Expression nullLiteral = Expression.Constant(null);
static readonly string keywordIt = "it";
static readonly string keywordIif = "iif";
static readonly string keywordNew = "new";
static Dictionary<string, object> keywords;
Dictionary<string, object> symbols;
IDictionary<string, object> externals;
Dictionary<Expression, string> literals;
ParameterExpression it;
string text;
int textPos;
int textLen;
char ch;
Token token;
public ExpressionParser(ParameterExpression[] parameters, string expression, object[] values)
{
if (expression == null) throw new ArgumentNullException("expression");
if (keywords == null) keywords = CreateKeywords();
symbols = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
literals = new Dictionary<Expression, string>();
if (parameters != null) ProcessParameters(parameters);
if (values != null) ProcessValues(values);
text = expression;
textLen = text.Length;
SetTextPos(0);
NextToken();
}
void ProcessParameters(ParameterExpression[] parameters)
{
foreach (ParameterExpression pe in parameters)
if (!String.IsNullOrEmpty(pe.Name))
AddSymbol(pe.Name, pe);
if (parameters.Length == 1 && String.IsNullOrEmpty(parameters[0].Name))
it = parameters[0];
}
void ProcessValues(object[] values)
{
for (int i = 0; i < values.Length; i++)
{
object value = values[i];
if (i == values.Length - 1 && value is IDictionary<string, object>)
{
externals = (IDictionary<string, object>)value;
}
else
{
AddSymbol("@" + i.ToString(System.Globalization.CultureInfo.InvariantCulture), value);
}
}
}
void AddSymbol(string name, object value)
{
if (symbols.ContainsKey(name))
throw ParseError(Res.DuplicateIdentifier, name);
symbols.Add(name, value);
}
public Expression Parse(Type resultType)
{
int exprPos = token.pos;
Expression expr = ParseExpression();
if (resultType != null)
if ((expr = PromoteExpression(expr, resultType, true)) == null)
throw ParseError(exprPos, Res.ExpressionTypeMismatch, GetTypeName(resultType));
ValidateToken(TokenId.End, Res.SyntaxError);
return expr;
}
#pragma warning disable 0219
public IEnumerable<DynamicOrdering> ParseOrdering()
{
List<DynamicOrdering> orderings = new List<DynamicOrdering>();
while (true)
{
Expression expr = ParseExpression();
bool ascending = true;
if (TokenIdentifierIs("asc") || TokenIdentifierIs("ascending"))
{
NextToken();
}
else if (TokenIdentifierIs("desc") || TokenIdentifierIs("descending"))
{
NextToken();
ascending = false;
}
orderings.Add(new DynamicOrdering { Selector = expr, Ascending = ascending });
if (token.id != TokenId.Comma) break;
NextToken();
}
ValidateToken(TokenId.End, Res.SyntaxError);
return orderings;
}
#pragma warning restore 0219
// ?: operator
Expression ParseExpression()
{
int errorPos = token.pos;
Expression expr = ParseLogicalOr();
if (token.id == TokenId.Question)
{
NextToken();
Expression expr1 = ParseExpression();
ValidateToken(TokenId.Colon, Res.ColonExpected);
NextToken();
Expression expr2 = ParseExpression();
expr = GenerateConditional(expr, expr1, expr2, errorPos);
}
return expr;
}
// ||, or operator
Expression ParseLogicalOr()
{
Expression left = ParseLogicalAnd();
while (token.id == TokenId.DoubleBar || TokenIdentifierIs("or"))
{
Token op = token;
NextToken();
Expression right = ParseLogicalAnd();
CheckAndPromoteOperands(typeof(ILogicalSignatures), op.text, ref left, ref right, op.pos);
left = Expression.OrElse(left, right);
}
return left;
}
// &&, and operator
Expression ParseLogicalAnd()
{
Expression left = ParseComparison();
while (token.id == TokenId.DoubleAmphersand || TokenIdentifierIs("and"))
{
Token op = token;
NextToken();
Expression right = ParseComparison();
CheckAndPromoteOperands(typeof(ILogicalSignatures), op.text, ref left, ref right, op.pos);
left = Expression.AndAlso(left, right);
}
return left;
}
// =, ==, !=, <>, >, >=, <, <= operators
Expression ParseComparison()
{
Expression left = ParseAdditive();
while (token.id == TokenId.Equal || token.id == TokenId.DoubleEqual ||
token.id == TokenId.ExclamationEqual || token.id == TokenId.LessGreater ||
token.id == TokenId.GreaterThan || token.id == TokenId.GreaterThanEqual ||
token.id == TokenId.LessThan || token.id == TokenId.LessThanEqual)
{
Token op = token;
NextToken();
Expression right = ParseAdditive();
bool isEquality = op.id == TokenId.Equal || op.id == TokenId.DoubleEqual ||
op.id == TokenId.ExclamationEqual || op.id == TokenId.LessGreater;
/// Guid workaround
/// http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2703782&SiteID=1
/// https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=333262
//if (isEquality && !left.Type.IsValueType && !right.Type.IsValueType)
bool leftOrRightTypeIsGuid =
(left.Type == typeof(Guid) || right.Type == typeof(Guid)
||
Nullable.GetUnderlyingType(left.Type) == typeof(Guid)
||
Nullable.GetUnderlyingType(right.Type) == typeof(Guid));
if (isEquality
&& ((!left.Type.IsValueType && !right.Type.IsValueType)
|| (left.Type == typeof(Guid) || right.Type == typeof(Guid))
|| leftOrRightTypeIsGuid
))
{
if (left.Type != right.Type)
{
if (left.Type.IsAssignableFrom(right.Type))
{
right = Expression.Convert(right, left.Type);
}
else if (right.Type.IsAssignableFrom(left.Type))
{
left = Expression.Convert(left, right.Type);
}
else
{
throw IncompatibleOperandsError(op.text, left, right, op.pos);
}
}
}
else if (IsEnumType(left.Type) || IsEnumType(right.Type))
{
if (left.Type != right.Type)
{
Expression e;
if ((e = PromoteExpression(right, left.Type, true)) != null)
{
right = e;
}
else if ((e = PromoteExpression(left, right.Type, true)) != null)
{
left = e;
}
else
{
throw IncompatibleOperandsError(op.text, left, right, op.pos);
}
}
}
else
{
CheckAndPromoteOperands(isEquality ? typeof(IEqualitySignatures) : typeof(IRelationalSignatures),
op.text, ref left, ref right, op.pos);
}
switch (op.id)
{
case TokenId.Equal:
case TokenId.DoubleEqual:
left = GenerateEqual(left, right);
break;
case TokenId.ExclamationEqual:
case TokenId.LessGreater:
left = GenerateNotEqual(left, right);
break;
case TokenId.GreaterThan:
left = GenerateGreaterThan(left, right);
break;
case TokenId.GreaterThanEqual:
left = GenerateGreaterThanEqual(left, right);
break;
case TokenId.LessThan:
left = GenerateLessThan(left, right);
break;
case TokenId.LessThanEqual:
left = GenerateLessThanEqual(left, right);
break;
}
}
return left;
}
// +, -, & operators
Expression ParseAdditive()
{
Expression left = ParseMultiplicative();
while (token.id == TokenId.Plus || token.id == TokenId.Minus ||
token.id == TokenId.Amphersand)
{
Token op = token;
NextToken();
Expression right = ParseMultiplicative();
switch (op.id)
{
case TokenId.Plus:
if (left.Type == typeof(string) || right.Type == typeof(string))
goto case TokenId.Amphersand;
CheckAndPromoteOperands(typeof(IAddSignatures), op.text, ref left, ref right, op.pos);
left = GenerateAdd(left, right);
break;
case TokenId.Minus:
CheckAndPromoteOperands(typeof(ISubtractSignatures), op.text, ref left, ref right, op.pos);
left = GenerateSubtract(left, right);
break;
case TokenId.Amphersand:
left = GenerateStringConcat(left, right);
break;
}
}
return left;
}
// *, /, %, mod operators
Expression ParseMultiplicative()
{
Expression left = ParseUnary();
while (token.id == TokenId.Asterisk || token.id == TokenId.Slash ||
token.id == TokenId.Percent || TokenIdentifierIs("mod"))
{
Token op = token;
NextToken();
Expression right = ParseUnary();
CheckAndPromoteOperands(typeof(IArithmeticSignatures), op.text, ref left, ref right, op.pos);
switch (op.id)
{
case TokenId.Asterisk:
left = Expression.Multiply(left, right);
break;
case TokenId.Slash:
left = Expression.Divide(left, right);
break;
case TokenId.Percent:
case TokenId.Identifier:
left = Expression.Modulo(left, right);
break;
}
}
return left;
}
// -, !, not unary operators
Expression ParseUnary()
{
if (token.id == TokenId.Minus || token.id == TokenId.Exclamation ||
TokenIdentifierIs("not"))
{
Token op = token;
NextToken();
if (op.id == TokenId.Minus && (token.id == TokenId.IntegerLiteral ||
token.id == TokenId.RealLiteral))
{
token.text = "-" + token.text;
token.pos = op.pos;
return ParsePrimary();
}
Expression expr = ParseUnary();
if (op.id == TokenId.Minus)
{
CheckAndPromoteOperand(typeof(INegationSignatures), op.text, ref expr, op.pos);
expr = Expression.Negate(expr);
}
else
{
CheckAndPromoteOperand(typeof(INotSignatures), op.text, ref expr, op.pos);
expr = Expression.Not(expr);
}
return expr;
}
return ParsePrimary();
}
Expression ParsePrimary()
{
Expression expr = ParsePrimaryStart();
while (true)
{
if (token.id == TokenId.Dot)
{
NextToken();
expr = ParseMemberAccess(null, expr);
}
else if (token.id == TokenId.OpenBracket)
{
expr = ParseElementAccess(expr);
}
else
{
break;
}
}
return expr;
}
Expression ParsePrimaryStart()
{
switch (token.id)
{
case TokenId.Identifier:
return ParseIdentifier();
case TokenId.StringLiteral:
return ParseStringLiteral();
case TokenId.IntegerLiteral:
return ParseIntegerLiteral();
case TokenId.RealLiteral:
return ParseRealLiteral();
case TokenId.OpenParen:
return ParseParenExpression();
default:
throw ParseError(Res.ExpressionExpected);
}
}
Expression ParseStringLiteral()
{
ValidateToken(TokenId.StringLiteral);
char quote = token.text[0];
string s = token.text.Substring(1, token.text.Length - 2);
int start = 0;
while (true)
{
int i = s.IndexOf(quote, start);
if (i < 0) break;
s = s.Remove(i, 1);
start = i + 1;
}
if (quote == '\'')
{
if (s.Length != 1)
throw ParseError(Res.InvalidCharacterLiteral);
NextToken();
return CreateLiteral(s[0], s);
}
NextToken();
return CreateLiteral(s, s);
}
Expression ParseIntegerLiteral()
{
ValidateToken(TokenId.IntegerLiteral);
string text = token.text;
if (text[0] != '-')
{
ulong value;
if (!UInt64.TryParse(text, out value))
throw ParseError(Res.InvalidIntegerLiteral, text);
NextToken();
if (value <= (ulong)Int32.MaxValue) return CreateLiteral((int)value, text);
if (value <= (ulong)UInt32.MaxValue) return CreateLiteral((uint)value, text);
if (value <= (ulong)Int64.MaxValue) return CreateLiteral((long)value, text);
return CreateLiteral(value, text);
}
else
{
long value;
if (!Int64.TryParse(text, out value))
throw ParseError(Res.InvalidIntegerLiteral, text);
NextToken();
if (value >= Int32.MinValue && value <= Int32.MaxValue)
return CreateLiteral((int)value, text);
return CreateLiteral(value, text);
}
}
Expression ParseRealLiteral()
{
ValidateToken(TokenId.RealLiteral);
string text = token.text;
object value = null;
char last = text[text.Length - 1];
if (last == 'F' || last == 'f')
{
float f;
if (Single.TryParse(text.Substring(0, text.Length - 1), out f)) value = f;
}
else
{
double d;
if (Double.TryParse(text, out d)) value = d;
}
if (value == null) throw ParseError(Res.InvalidRealLiteral, text);
NextToken();
return CreateLiteral(value, text);
}
Expression CreateLiteral(object value, string text)
{
ConstantExpression expr = Expression.Constant(value);
literals.Add(expr, text);
return expr;
}
Expression ParseParenExpression()
{
ValidateToken(TokenId.OpenParen, Res.OpenParenExpected);
NextToken();
Expression e = ParseExpression();
ValidateToken(TokenId.CloseParen, Res.CloseParenOrOperatorExpected);
NextToken();
return e;
}
Expression ParseIdentifier()
{
ValidateToken(TokenId.Identifier);
object value;
if (keywords.TryGetValue(token.text, out value))
{
if (value is Type) return ParseTypeAccess((Type)value);
if (value == (object)keywordIt) return ParseIt();
if (value == (object)keywordIif) return ParseIif();
if (value == (object)keywordNew) return ParseNew();
NextToken();
return (Expression)value;
}
if (symbols.TryGetValue(token.text, out value) ||
externals != null && externals.TryGetValue(token.text, out value))
{
Expression expr = value as Expression;
if (expr == null)
{
expr = Expression.Constant(value);
}
else
{
LambdaExpression lambda = expr as LambdaExpression;
if (lambda != null) return ParseLambdaInvocation(lambda);
}
NextToken();
return expr;
}
if (it != null) return ParseMemberAccess(null, it);
throw ParseError(Res.UnknownIdentifier, token.text);
}
Expression ParseIt()
{
if (it == null)
throw ParseError(Res.NoItInScope);
NextToken();
return it;
}
Expression ParseIif()
{
int errorPos = token.pos;
NextToken();
Expression[] args = ParseArgumentList();
if (args.Length != 3)
throw ParseError(errorPos, Res.IifRequiresThreeArgs);
return GenerateConditional(args[0], args[1], args[2], errorPos);
}
Expression GenerateConditional(Expression test, Expression expr1, Expression expr2, int errorPos)
{
if (test.Type != typeof(bool))
throw ParseError(errorPos, Res.FirstExprMustBeBool);
if (expr1.Type != expr2.Type)
{
Expression expr1as2 = expr2 != nullLiteral ? PromoteExpression(expr1, expr2.Type, true) : null;
Expression expr2as1 = expr1 != nullLiteral ? PromoteExpression(expr2, expr1.Type, true) : null;
if (expr1as2 != null && expr2as1 == null)
{
expr1 = expr1as2;
}
else if (expr2as1 != null && expr1as2 == null)
{
expr2 = expr2as1;
}
else
{
string type1 = expr1 != nullLiteral ? expr1.Type.Name : "null";
string type2 = expr2 != nullLiteral ? expr2.Type.Name : "null";
if (expr1as2 != null && expr2as1 != null)
throw ParseError(errorPos, Res.BothTypesConvertToOther, type1, type2);
throw ParseError(errorPos, Res.NeitherTypeConvertsToOther, type1, type2);
}
}
return Expression.Condition(test, expr1, expr2);
}
Expression ParseNew()
{
NextToken();
ValidateToken(TokenId.OpenParen, Res.OpenParenExpected);
NextToken();
List<DynamicProperty> properties = new List<DynamicProperty>();
List<Expression> expressions = new List<Expression>();
while (true)
{
int exprPos = token.pos;
Expression expr = ParseExpression();
string propName;
if (TokenIdentifierIs("as"))
{
NextToken();
propName = GetIdentifier();
NextToken();
}
else
{
MemberExpression me = expr as MemberExpression;
if (me == null) throw ParseError(exprPos, Res.MissingAsClause);
propName = me.Member.Name;
}
expressions.Add(expr);
properties.Add(new DynamicProperty(propName, expr.Type));
if (token.id != TokenId.Comma) break;
NextToken();
}
ValidateToken(TokenId.CloseParen, Res.CloseParenOrCommaExpected);
NextToken();
Type type = DynamicExpression.CreateClass(properties);
MemberBinding[] bindings = new MemberBinding[properties.Count];
for (int i = 0; i < bindings.Length; i++)
bindings[i] = Expression.Bind(type.GetProperty(properties[i].Name), expressions[i]);
return Expression.MemberInit(Expression.New(type), bindings);
}
Expression ParseLambdaInvocation(LambdaExpression lambda)
{
int errorPos = token.pos;
NextToken();
Expression[] args = ParseArgumentList();
MethodBase method;
if (FindMethod(lambda.Type, "Invoke", false, args, out method) != 1)
throw ParseError(errorPos, Res.ArgsIncompatibleWithLambda);
return Expression.Invoke(lambda, args);
}
Expression ParseTypeAccess(Type type)
{
int errorPos = token.pos;
NextToken();
if (token.id == TokenId.Question)
{
if (!type.IsValueType || IsNullableType(type))
throw ParseError(errorPos, Res.TypeHasNoNullableForm, GetTypeName(type));
type = typeof(Nullable<>).MakeGenericType(type);
NextToken();
}
if (token.id == TokenId.OpenParen)
{
Expression[] args = ParseArgumentList();
MethodBase method;
switch (FindBestMethod(type.GetConstructors(), args, out method))
{
case 0:
if (args.Length == 1)
return GenerateConversion(args[0], type, errorPos);
throw ParseError(errorPos, Res.NoMatchingConstructor, GetTypeName(type));
case 1:
return Expression.New((ConstructorInfo)method, args);
default:
throw ParseError(errorPos, Res.AmbiguousConstructorInvocation, GetTypeName(type));
}
}
ValidateToken(TokenId.Dot, Res.DotOrOpenParenExpected);
NextToken();
return ParseMemberAccess(type, null);
}
Expression GenerateConversion(Expression expr, Type type, int errorPos)
{
Type exprType = expr.Type;
if (exprType == type) return expr;
if (exprType.IsValueType && type.IsValueType)
{
if ((IsNullableType(exprType) || IsNullableType(type)) &&
GetNonNullableType(exprType) == GetNonNullableType(type))
return Expression.Convert(expr, type);
if ((IsNumericType(exprType) || IsEnumType(exprType)) &&
(IsNumericType(type)) || IsEnumType(type))
return Expression.ConvertChecked(expr, type);
}
if (exprType.IsAssignableFrom(type) || type.IsAssignableFrom(exprType) ||
exprType.IsInterface || type.IsInterface)
return Expression.Convert(expr, type);
throw ParseError(errorPos, Res.CannotConvertValue,
GetTypeName(exprType), GetTypeName(type));
}
Expression ParseMemberAccess(Type type, Expression instance)
{
if (instance != null) type = instance.Type;
int errorPos = token.pos;
string id = GetIdentifier();
NextToken();
if (token.id == TokenId.OpenParen)
{
if (instance != null && type != typeof(string))
{
Type enumerableType = FindGenericType(typeof(IEnumerable<>), type);
if (enumerableType != null)
{
Type elementType = enumerableType.GetGenericArguments()[0];
return ParseAggregate(instance, elementType, id, errorPos);
}
}
Expression[] args = ParseArgumentList();
MethodBase mb;
switch (FindMethod(type, id, instance == null, args, out mb))
{
case 0:
throw ParseError(errorPos, Res.NoApplicableMethod,
id, GetTypeName(type));
case 1:
MethodInfo method = (MethodInfo)mb;
if (!IsPredefinedType(method.DeclaringType))
throw ParseError(errorPos, Res.MethodsAreInaccessible, GetTypeName(method.DeclaringType));
if (method.ReturnType == typeof(void))
throw ParseError(errorPos, Res.MethodIsVoid,
id, GetTypeName(method.DeclaringType));
return Expression.Call(instance, (MethodInfo)method, args);
default:
throw ParseError(errorPos, Res.AmbiguousMethodInvocation,
id, GetTypeName(type));
}
}
else
{
MemberInfo member = FindPropertyOrField(type, id, instance == null);
if (member == null)
throw ParseError(errorPos, Res.UnknownPropertyOrField,
id, GetTypeName(type));
return member is PropertyInfo ?
Expression.Property(instance, (PropertyInfo)member) :
Expression.Field(instance, (FieldInfo)member);
}
}
static Type FindGenericType(Type generic, Type type)
{
while (type != null && type != typeof(object))
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == generic) return type;
if (generic.IsInterface)
{
foreach (Type intfType in type.GetInterfaces())
{
Type found = FindGenericType(generic, intfType);
if (found != null) return found;
}
}
type = type.BaseType;
}
return null;
}
Expression ParseAggregate(Expression instance, Type elementType, string methodName, int errorPos)
{
ParameterExpression outerIt = it;
ParameterExpression innerIt = Expression.Parameter(elementType, "");
it = innerIt;
Expression[] args = ParseArgumentList();
it = outerIt;
MethodBase signature;
if (FindMethod(typeof(IEnumerableSignatures), methodName, false, args, out signature) != 1)
throw ParseError(errorPos, Res.NoApplicableAggregate, methodName);
Type[] typeArgs;
if (signature.Name == "Min" || signature.Name == "Max")
{
typeArgs = new Type[] { elementType, args[0].Type };
}
else
{
typeArgs = new Type[] { elementType };
}
if (args.Length == 0)
{
args = new Expression[] { instance };
}
else
{
args = new Expression[] { instance, Expression.Lambda(args[0], innerIt) };
}
return Expression.Call(typeof(Enumerable), signature.Name, typeArgs, args);
}
Expression[] ParseArgumentList()
{
ValidateToken(TokenId.OpenParen, Res.OpenParenExpected);
NextToken();
Expression[] args = token.id != TokenId.CloseParen ? ParseArguments() : new Expression[0];
ValidateToken(TokenId.CloseParen, Res.CloseParenOrCommaExpected);
NextToken();
return args;
}
Expression[] ParseArguments()
{
List<Expression> argList = new List<Expression>();
while (true)
{
argList.Add(ParseExpression());
if (token.id != TokenId.Comma) break;
NextToken();
}
return argList.ToArray();
}
Expression ParseElementAccess(Expression expr)
{
int errorPos = token.pos;
ValidateToken(TokenId.OpenBracket, Res.OpenParenExpected);
NextToken();
Expression[] args = ParseArguments();
ValidateToken(TokenId.CloseBracket, Res.CloseBracketOrCommaExpected);
NextToken();
if (expr.Type.IsArray)
{
if (expr.Type.GetArrayRank() != 1 || args.Length != 1)
throw ParseError(errorPos, Res.CannotIndexMultiDimArray);
Expression index = PromoteExpression(args[0], typeof(int), true);
if (index == null)
throw ParseError(errorPos, Res.InvalidIndex);
return Expression.ArrayIndex(expr, index);
}
else
{
MethodBase mb;
switch (FindIndexer(expr.Type, args, out mb))
{
case 0:
throw ParseError(errorPos, Res.NoApplicableIndexer,
GetTypeName(expr.Type));
case 1:
return Expression.Call(expr, (MethodInfo)mb, args);
default:
throw ParseError(errorPos, Res.AmbiguousIndexerInvocation,
GetTypeName(expr.Type));
}
}
}
static bool IsPredefinedType(Type type)
{
foreach (Type t in predefinedTypes) if (t == type) return true;
return false;
}
static bool IsNullableType(Type type)
{
return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
static Type GetNonNullableType(Type type)
{
return IsNullableType(type) ? type.GetGenericArguments()[0] : type;
}
static string GetTypeName(Type type)
{
Type baseType = GetNonNullableType(type);
string s = baseType.Name;
if (type != baseType) s += '?';
return s;
}
static bool IsNumericType(Type type)
{
return GetNumericTypeKind(type) != 0;
}
static bool IsSignedIntegralType(Type type)
{
return GetNumericTypeKind(type) == 2;
}
static bool IsUnsignedIntegralType(Type type)
{
return GetNumericTypeKind(type) == 3;
}
static int GetNumericTypeKind(Type type)
{
type = GetNonNullableType(type);
if (type.IsEnum) return 0;
switch (Type.GetTypeCode(type))
{
case TypeCode.Char:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return 1;
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
return 2;
case TypeCode.Byte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return 3;
default:
return 0;
}
}
static bool IsEnumType(Type type)
{
return GetNonNullableType(type).IsEnum;
}
void CheckAndPromoteOperand(Type signatures, string opName, ref Expression expr, int errorPos)
{
Expression[] args = new Expression[] { expr };
MethodBase method;
if (FindMethod(signatures, "F", false, args, out method) != 1)
throw ParseError(errorPos, Res.IncompatibleOperand,
opName, GetTypeName(args[0].Type));
expr = args[0];
}
void CheckAndPromoteOperands(Type signatures, string opName, ref Expression left, ref Expression right, int errorPos)
{
Expression[] args = new Expression[] { left, right };
MethodBase method;
if (FindMethod(signatures, "F", false, args, out method) != 1)
throw IncompatibleOperandsError(opName, left, right, errorPos);
left = args[0];
right = args[1];
}
Exception IncompatibleOperandsError(string opName, Expression left, Expression right, int pos)
{
return ParseError(pos, Res.IncompatibleOperands,
opName, GetTypeName(left.Type), GetTypeName(right.Type));
}
MemberInfo FindPropertyOrField(Type type, string memberName, bool staticAccess)
{
BindingFlags flags = BindingFlags.Public | BindingFlags.DeclaredOnly |
(staticAccess ? BindingFlags.Static : BindingFlags.Instance);
foreach (Type t in SelfAndBaseTypes(type))
{
MemberInfo[] members = t.FindMembers(MemberTypes.Property | MemberTypes.Field,
flags, Type.FilterNameIgnoreCase, memberName);
if (members.Length != 0) return members[0];
}
return null;
}
int FindMethod(Type type, string methodName, bool staticAccess, Expression[] args, out MethodBase method)
{
BindingFlags flags = BindingFlags.Public | BindingFlags.DeclaredOnly |
(staticAccess ? BindingFlags.Static : BindingFlags.Instance);
foreach (Type t in SelfAndBaseTypes(type))
{
MemberInfo[] members = t.FindMembers(MemberTypes.Method,
flags, Type.FilterNameIgnoreCase, methodName);
int count = FindBestMethod(members.Cast<MethodBase>(), args, out method);
if (count != 0) return count;
}
method = null;
return 0;
}
int FindIndexer(Type type, Expression[] args, out MethodBase method)
{
foreach (Type t in SelfAndBaseTypes(type))
{
MemberInfo[] members = t.GetDefaultMembers();
if (members.Length != 0)
{
IEnumerable<MethodBase> methods = members.
OfType<PropertyInfo>().
Select(p => (MethodBase)p.GetGetMethod()).
Where(m => m != null);
int count = FindBestMethod(methods, args, out method);
if (count != 0) return count;
}
}
method = null;
return 0;
}
static IEnumerable<Type> SelfAndBaseTypes(Type type)
{
if (type.IsInterface)
{
List<Type> types = new List<Type>();
AddInterface(types, type);
return types;
}
return SelfAndBaseClasses(type);
}
static IEnumerable<Type> SelfAndBaseClasses(Type type)
{
while (type != null)
{
yield return type;
type = type.BaseType;
}
}
static void AddInterface(List<Type> types, Type type)
{
if (!types.Contains(type))
{
types.Add(type);
foreach (Type t in type.GetInterfaces()) AddInterface(types, t);
}
}
class MethodData
{
public MethodBase MethodBase;
public ParameterInfo[] Parameters;
public Expression[] Args;
}
int FindBestMethod(IEnumerable<MethodBase> methods, Expression[] args, out MethodBase method)
{
MethodData[] applicable = methods.
Select(m => new MethodData { MethodBase = m, Parameters = m.GetParameters() }).
Where(m => IsApplicable(m, args)).
ToArray();
if (applicable.Length > 1)
{
applicable = applicable.
Where(m => applicable.All(n => m == n || IsBetterThan(args, m, n))).
ToArray();
}
if (applicable.Length == 1)
{
MethodData md = applicable[0];
for (int i = 0; i < args.Length; i++) args[i] = md.Args[i];
method = md.MethodBase;
}
else
{
method = null;
}
return applicable.Length;
}
bool IsApplicable(MethodData method, Expression[] args)
{
if (method.Parameters.Length != args.Length) return false;
Expression[] promotedArgs = new Expression[args.Length];
for (int i = 0; i < args.Length; i++)
{
ParameterInfo pi = method.Parameters[i];
if (pi.IsOut) return false;
Expression promoted = PromoteExpression(args[i], pi.ParameterType, false);
if (promoted == null) return false;
promotedArgs[i] = promoted;
}
method.Args = promotedArgs;
return true;
}
Expression PromoteExpression(Expression expr, Type type, bool exact)
{
if (expr.Type == type) return expr;
if (expr is ConstantExpression)
{
ConstantExpression ce = (ConstantExpression)expr;
if (ce == nullLiteral)
{
if (!type.IsValueType || IsNullableType(type))
return Expression.Constant(null, type);
}
else
{
string text;
if (literals.TryGetValue(ce, out text))
{
Type target = GetNonNullableType(type);
Object value = null;
switch (Type.GetTypeCode(ce.Type))
{
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
value = ParseNumber(text, target);
break;
case TypeCode.Double:
if (target == typeof(decimal)) value = ParseNumber(text, target);
break;
case TypeCode.String:
value = ParseEnum(text, target);
break;
}
if (value != null)
return Expression.Constant(value, type);
}
}
}
if (IsCompatibleWith(expr.Type, type))
{
if (type.IsValueType || exact) return Expression.Convert(expr, type);
return expr;
}
return null;
}
static object ParseNumber(string text, Type type)
{
switch (Type.GetTypeCode(GetNonNullableType(type)))
{
case TypeCode.SByte:
sbyte sb;
if (sbyte.TryParse(text, out sb)) return sb;
break;
case TypeCode.Byte:
byte b;
if (byte.TryParse(text, out b)) return b;
break;
case TypeCode.Int16:
short s;
if (short.TryParse(text, out s)) return s;
break;
case TypeCode.UInt16:
ushort us;
if (ushort.TryParse(text, out us)) return us;
break;
case TypeCode.Int32:
int i;
if (int.TryParse(text, out i)) return i;
break;
case TypeCode.UInt32:
uint ui;
if (uint.TryParse(text, out ui)) return ui;
break;
case TypeCode.Int64:
long l;
if (long.TryParse(text, out l)) return l;
break;
case TypeCode.UInt64:
ulong ul;
if (ulong.TryParse(text, out ul)) return ul;
break;
case TypeCode.Single:
float f;
if (float.TryParse(text, out f)) return f;
break;
case TypeCode.Double:
double d;
if (double.TryParse(text, out d)) return d;
break;
case TypeCode.Decimal:
decimal e;
if (decimal.TryParse(text, out e)) return e;
break;
}
return null;
}
static object ParseEnum(string name, Type type)
{
if (type.IsEnum)
{
MemberInfo[] memberInfos = type.FindMembers(MemberTypes.Field,
BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Static,
Type.FilterNameIgnoreCase, name);
if (memberInfos.Length != 0) return ((FieldInfo)memberInfos[0]).GetValue(null);
}
return null;
}
static bool IsCompatibleWith(Type source, Type target)
{
if (source == target) return true;
if (!target.IsValueType) return target.IsAssignableFrom(source);
Type st = GetNonNullableType(source);
Type tt = GetNonNullableType(target);
if (st != source && tt == target) return false;
TypeCode sc = st.IsEnum ? TypeCode.Object : Type.GetTypeCode(st);
TypeCode tc = tt.IsEnum ? TypeCode.Object : Type.GetTypeCode(tt);
switch (sc)
{
case TypeCode.SByte:
switch (tc)
{
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Byte:
switch (tc)
{
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Int16:
switch (tc)
{
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.UInt16:
switch (tc)
{
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Int32:
switch (tc)
{
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.UInt32:
switch (tc)
{
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Int64:
switch (tc)
{
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.UInt64:
switch (tc)
{
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Single:
switch (tc)
{
case TypeCode.Single:
case TypeCode.Double:
return true;
}
break;
default:
if (st == tt) return true;
break;
}
return false;
}
static bool IsBetterThan(Expression[] args, MethodData m1, MethodData m2)
{
bool better = false;
for (int i = 0; i < args.Length; i++)
{
int c = CompareConversions(args[i].Type,
m1.Parameters[i].ParameterType,
m2.Parameters[i].ParameterType);
if (c < 0) return false;
if (c > 0) better = true;
}
return better;
}
// Return 1 if s -> t1 is a better conversion than s -> t2
// Return -1 if s -> t2 is a better conversion than s -> t1
// Return 0 if neither conversion is better
static int CompareConversions(Type s, Type t1, Type t2)
{
if (t1 == t2) return 0;
if (s == t1) return 1;
if (s == t2) return -1;
bool t1t2 = IsCompatibleWith(t1, t2);
bool t2t1 = IsCompatibleWith(t2, t1);
if (t1t2 && !t2t1) return 1;
if (t2t1 && !t1t2) return -1;
if (IsSignedIntegralType(t1) && IsUnsignedIntegralType(t2)) return 1;
if (IsSignedIntegralType(t2) && IsUnsignedIntegralType(t1)) return -1;
return 0;
}
Expression GenerateEqual(Expression left, Expression right)
{
return Expression.Equal(left, right);
}
Expression GenerateNotEqual(Expression left, Expression right)
{
return Expression.NotEqual(left, right);
}
Expression GenerateGreaterThan(Expression left, Expression right)
{
if (left.Type == typeof(string))
{
return Expression.GreaterThan(
GenerateStaticMethodCall("Compare", left, right),
Expression.Constant(0)
);
}
return Expression.GreaterThan(left, right);
}
Expression GenerateGreaterThanEqual(Expression left, Expression right)
{
if (left.Type == typeof(string))
{
return Expression.GreaterThanOrEqual(
GenerateStaticMethodCall("Compare", left, right),
Expression.Constant(0)
);
}
return Expression.GreaterThanOrEqual(left, right);
}
Expression GenerateLessThan(Expression left, Expression right)
{
if (left.Type == typeof(string))
{
return Expression.LessThan(
GenerateStaticMethodCall("Compare", left, right),
Expression.Constant(0)
);
}
return Expression.LessThan(left, right);
}
Expression GenerateLessThanEqual(Expression left, Expression right)
{
if (left.Type == typeof(string))
{
return Expression.LessThanOrEqual(
GenerateStaticMethodCall("Compare", left, right),
Expression.Constant(0)
);
}
return Expression.LessThanOrEqual(left, right);
}
Expression GenerateAdd(Expression left, Expression right)
{
if (left.Type == typeof(string) && right.Type == typeof(string))
{
return GenerateStaticMethodCall("Concat", left, right);
}
return Expression.Add(left, right);
}
Expression GenerateSubtract(Expression left, Expression right)
{
return Expression.Subtract(left, right);
}
Expression GenerateStringConcat(Expression left, Expression right)
{
return Expression.Call(
null,
typeof(string).GetMethod("Concat", new[] { typeof(object), typeof(object) }),
new[] { left, right });
}
MethodInfo GetStaticMethod(string methodName, Expression left, Expression right)
{
return left.Type.GetMethod(methodName, new[] { left.Type, right.Type });
}
Expression GenerateStaticMethodCall(string methodName, Expression left, Expression right)
{
return Expression.Call(null, GetStaticMethod(methodName, left, right), new[] { left, right });
}
void SetTextPos(int pos)
{
textPos = pos;
ch = textPos < textLen ? text[textPos] : '\0';
}
void NextChar()
{
if (textPos < textLen) textPos++;
ch = textPos < textLen ? text[textPos] : '\0';
}
void NextToken()
{
while (Char.IsWhiteSpace(ch)) NextChar();
TokenId t;
int tokenPos = textPos;
switch (ch)
{
case '!':
NextChar();
if (ch == '=')
{
NextChar();
t = TokenId.ExclamationEqual;
}
else
{
t = TokenId.Exclamation;
}
break;
case '%':
NextChar();
t = TokenId.Percent;
break;
case '&':
NextChar();
if (ch == '&')
{
NextChar();
t = TokenId.DoubleAmphersand;
}
else
{
t = TokenId.Amphersand;
}
break;
case '(':
NextChar();
t = TokenId.OpenParen;
break;
case ')':
NextChar();
t = TokenId.CloseParen;
break;
case '*':
NextChar();
t = TokenId.Asterisk;
break;
case '+':
NextChar();
t = TokenId.Plus;
break;
case ',':
NextChar();
t = TokenId.Comma;
break;
case '-':
NextChar();
t = TokenId.Minus;
break;
case '.':
NextChar();
t = TokenId.Dot;
break;
case '/':
NextChar();
t = TokenId.Slash;
break;
case ':':
NextChar();
t = TokenId.Colon;
break;
case '<':
NextChar();
if (ch == '=')
{
NextChar();
t = TokenId.LessThanEqual;
}
else if (ch == '>')
{
NextChar();
t = TokenId.LessGreater;
}
else
{
t = TokenId.LessThan;
}
break;
case '=':
NextChar();
if (ch == '=')
{
NextChar();
t = TokenId.DoubleEqual;
}
else
{
t = TokenId.Equal;
}
break;
case '>':
NextChar();
if (ch == '=')
{
NextChar();
t = TokenId.GreaterThanEqual;
}
else
{
t = TokenId.GreaterThan;
}
break;
case '?':
NextChar();
t = TokenId.Question;
break;
case '[':
NextChar();
t = TokenId.OpenBracket;
break;
case ']':
NextChar();
t = TokenId.CloseBracket;
break;
case '|':
NextChar();
if (ch == '|')
{
NextChar();
t = TokenId.DoubleBar;
}
else
{
t = TokenId.Bar;
}
break;
case '"':
case '\'':
char quote = ch;
do
{
NextChar();
while (textPos < textLen && ch != quote) NextChar();
if (textPos == textLen)
throw ParseError(textPos, Res.UnterminatedStringLiteral);
NextChar();
} while (ch == quote);
t = TokenId.StringLiteral;
break;
default:
if (Char.IsLetter(ch) || ch == '@' || ch == '_')
{
do
{
NextChar();
} while (Char.IsLetterOrDigit(ch) || ch == '_');
t = TokenId.Identifier;
break;
}
if (Char.IsDigit(ch))
{
t = TokenId.IntegerLiteral;
do
{
NextChar();
} while (Char.IsDigit(ch));
if (ch == '.')
{
t = TokenId.RealLiteral;
NextChar();
ValidateDigit();
do
{
NextChar();
} while (Char.IsDigit(ch));
}
if (ch == 'E' || ch == 'e')
{
t = TokenId.RealLiteral;
NextChar();
if (ch == '+' || ch == '-') NextChar();
ValidateDigit();
do
{
NextChar();
} while (Char.IsDigit(ch));
}
if (ch == 'F' || ch == 'f') NextChar();
break;
}
if (textPos == textLen)
{
t = TokenId.End;
break;
}
throw ParseError(textPos, Res.InvalidCharacter, ch);
}
token.id = t;
token.text = text.Substring(tokenPos, textPos - tokenPos);
token.pos = tokenPos;
}
bool TokenIdentifierIs(string id)
{
return token.id == TokenId.Identifier && String.Equals(id, token.text, StringComparison.OrdinalIgnoreCase);
}
string GetIdentifier()
{
ValidateToken(TokenId.Identifier, Res.IdentifierExpected);
string id = token.text;
if (id.Length > 1 && id[0] == '@') id = id.Substring(1);
return id;
}
void ValidateDigit()
{
if (!Char.IsDigit(ch)) throw ParseError(textPos, Res.DigitExpected);
}
void ValidateToken(TokenId t, string errorMessage)
{
if (token.id != t) throw ParseError(errorMessage);
}
void ValidateToken(TokenId t)
{
if (token.id != t) throw ParseError(Res.SyntaxError);
}
Exception ParseError(string format, params object[] args)
{
return ParseError(token.pos, format, args);
}
Exception ParseError(int pos, string format, params object[] args)
{
return new ParseException(string.Format(System.Globalization.CultureInfo.CurrentCulture, format, args), pos);
}
static Dictionary<string, object> CreateKeywords()
{
Dictionary<string, object> d = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
d.Add("true", trueLiteral);
d.Add("false", falseLiteral);
d.Add("null", nullLiteral);
d.Add(keywordIt, keywordIt);
d.Add(keywordIif, keywordIif);
d.Add(keywordNew, keywordNew);
foreach (Type type in predefinedTypes) d.Add(type.Name, type);
return d;
}
}
static class Res
{
public const string DuplicateIdentifier = "The identifier '{0}' was defined more than once";
public const string ExpressionTypeMismatch = "Expression of type '{0}' expected";
public const string ExpressionExpected = "Expression expected";
public const string InvalidCharacterLiteral = "Character literal must contain exactly one character";
public const string InvalidIntegerLiteral = "Invalid integer literal '{0}'";
public const string InvalidRealLiteral = "Invalid real literal '{0}'";
public const string UnknownIdentifier = "Unknown identifier '{0}'";
public const string NoItInScope = "No 'it' is in scope";
public const string IifRequiresThreeArgs = "The 'iif' function requires three arguments";
public const string FirstExprMustBeBool = "The first expression must be of type 'Boolean'";
public const string BothTypesConvertToOther = "Both of the types '{0}' and '{1}' convert to the other";
public const string NeitherTypeConvertsToOther = "Neither of the types '{0}' and '{1}' converts to the other";
public const string MissingAsClause = "Expression is missing an 'as' clause";
public const string ArgsIncompatibleWithLambda = "Argument list incompatible with lambda expression";
public const string TypeHasNoNullableForm = "Type '{0}' has no nullable form";
public const string NoMatchingConstructor = "No matching constructor in type '{0}'";
public const string AmbiguousConstructorInvocation = "Ambiguous invocation of '{0}' constructor";
public const string CannotConvertValue = "A value of type '{0}' cannot be converted to type '{1}'";
public const string NoApplicableMethod = "No applicable method '{0}' exists in type '{1}'";
public const string MethodsAreInaccessible = "Methods on type '{0}' are not accessible";
public const string MethodIsVoid = "Method '{0}' in type '{1}' does not return a value";
public const string AmbiguousMethodInvocation = "Ambiguous invocation of method '{0}' in type '{1}'";
public const string UnknownPropertyOrField = "No property or field '{0}' exists in type '{1}'";
public const string NoApplicableAggregate = "No applicable aggregate method '{0}' exists";
public const string CannotIndexMultiDimArray = "Indexing of multi-dimensional arrays is not supported";
public const string InvalidIndex = "Array index must be an integer expression";
public const string NoApplicableIndexer = "No applicable indexer exists in type '{0}'";
public const string AmbiguousIndexerInvocation = "Ambiguous invocation of indexer in type '{0}'";
public const string IncompatibleOperand = "Operator '{0}' incompatible with operand type '{1}'";
public const string IncompatibleOperands = "Operator '{0}' incompatible with operand types '{1}' and '{2}'";
public const string UnterminatedStringLiteral = "Unterminated string literal";
public const string InvalidCharacter = "Syntax error '{0}'";
public const string DigitExpected = "Digit expected";
public const string SyntaxError = "Syntax error";
public const string TokenExpected = "{0} expected";
public const string ParseExceptionFormat = "{0} (at index {1})";
public const string ColonExpected = "':' expected";
public const string OpenParenExpected = "'(' expected";
public const string CloseParenOrOperatorExpected = "')' or operator expected";
public const string CloseParenOrCommaExpected = "')' or ',' expected";
public const string DotOrOpenParenExpected = "'.' or '(' expected";
public const string OpenBracketExpected = "'[' expected";
public const string CloseBracketOrCommaExpected = "']' or ',' expected";
public const string IdentifierExpected = "Identifier expected";
}
}
| zzgaminginc-pointofssale | Lib/DataGridFilterLibrary/Support/DynamicLibrary.cs | C# | gpl3 | 90,060 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace DataGridFilterLibrary.Support
{
[Serializable()]
public class FilterData : INotifyPropertyChanged
{
#region Metadata
public FilterType Type { get; set; }
public String ValuePropertyBindingPath { get; set; }
public Type ValuePropertyType { get; set; }
public bool IsTypeInitialized { get; set; }
public bool IsCaseSensitiveSearch { get; set; }
//query optimization fileds
public bool IsSearchPerformed { get; set; }
public bool IsRefresh { get; set; }
//query optimization fileds
#endregion
#region Filter Change Notification
public event EventHandler<EventArgs> FilterChangedEvent;
private bool isClearData;
private void OnFilterChangedEvent()
{
EventHandler<EventArgs> temp = FilterChangedEvent;
if (temp != null)
{
bool filterChanged = false;
switch (Type)
{
case FilterType.Numeric:
case FilterType.DateTime:
filterChanged = (Operator != FilterOperator.Undefined || QueryString != String.Empty);
break;
case FilterType.NumericBetween:
case FilterType.DateTimeBetween:
_operator = FilterOperator.Between;
filterChanged = true;
break;
case FilterType.Text:
_operator = FilterOperator.Like;
filterChanged = true;
break;
case FilterType.List:
case FilterType.Boolean:
_operator = FilterOperator.Equals;
filterChanged = true;
break;
default:
filterChanged = false;
break;
}
if (filterChanged && !isClearData) temp(this, EventArgs.Empty);
}
}
#endregion
public void ClearData()
{
isClearData = true;
Operator = FilterOperator.Undefined;
if (QueryString != String.Empty) QueryString = null;
if (QueryStringTo != String.Empty) QueryStringTo = null;
isClearData = false;
}
private FilterOperator _operator;
public FilterOperator Operator
{
get { return _operator; }
set
{
if(_operator != value)
{
_operator = value;
NotifyPropertyChanged("Operator");
OnFilterChangedEvent();
}
}
}
private string queryString;
public string QueryString
{
get { return queryString; }
set
{
if (queryString != value)
{
queryString = value;
if (queryString == null) queryString = String.Empty;
NotifyPropertyChanged("QueryString");
OnFilterChangedEvent();
}
}
}
private string queryStringTo;
public string QueryStringTo
{
get { return queryStringTo; }
set
{
if (queryStringTo != value)
{
queryStringTo = value;
if (queryStringTo == null) queryStringTo = String.Empty;
NotifyPropertyChanged("QueryStringTo");
OnFilterChangedEvent();
}
}
}
public FilterData(
FilterOperator Operator,
FilterType Type,
String ValuePropertyBindingPath,
Type ValuePropertyType,
String QueryString,
String QueryStringTo,
bool IsTypeInitialized,
bool IsCaseSensitiveSearch
)
{
this.Operator = Operator;
this.Type = Type;
this.ValuePropertyBindingPath = ValuePropertyBindingPath;
this.ValuePropertyType = ValuePropertyType;
this.QueryString = QueryString;
this.QueryStringTo = QueryStringTo;
this.IsTypeInitialized = IsTypeInitialized;
this.IsCaseSensitiveSearch = IsCaseSensitiveSearch;
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| zzgaminginc-pointofssale | Lib/DataGridFilterLibrary/Support/FilterData.cs | C# | gpl3 | 5,162 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Globalization;
namespace DataGridFilterLibrary.Support
{
public class BooleanToHeightConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((bool)value)
{
return Double.NaN;
}
else
{
return 0;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
}
| zzgaminginc-pointofssale | Lib/DataGridFilterLibrary/Support/BooleanToHeightConverter.cs | C# | gpl3 | 724 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Globalization;
namespace DataGridFilterLibrary.Support
{
public class FontSizeToHeightConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double height;
if (value != null)
{
if(Double.TryParse(value.ToString(), out height))
{
return height * 2;
}
else
{
return Double.NaN;
}
}
else
{
return value;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
}
| zzgaminginc-pointofssale | Lib/DataGridFilterLibrary/Support/FontSizeToHeightConverter.cs | C# | gpl3 | 988 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Globalization;
namespace DataGridFilterLibrary.Support
{
public class VisibilityToWidthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
System.Windows.Visibility visibility = (System.Windows.Visibility)value;
return visibility == System.Windows.Visibility.Visible ? Double.NaN : 0;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
}
| zzgaminginc-pointofssale | Lib/DataGridFilterLibrary/Support/VisibilityToWidthConverter.cs | C# | gpl3 | 729 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Globalization;
namespace DataGridFilterLibrary.Support
{
public class MyBooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((bool)value)
{
return System.Windows.Visibility.Visible;
}
else
{
return System.Windows.Visibility.Collapsed;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
System.Windows.Visibility visibility = (System.Windows.Visibility)value;
return visibility == System.Windows.Visibility.Visible ? true : false;
}
}
}
| zzgaminginc-pointofssale | Lib/DataGridFilterLibrary/Support/MyBooleanToVisibilityConverter.cs | C# | gpl3 | 932 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DataGridFilterLibrary.Support
{
/// <summary>
/// Corresponds to the FilterCurrentData templates (DataTemplate)
/// of the DataGridColumnFilter defined in the Generic.xaml>
/// </summary>
public enum FilterType
{
Numeric,
NumericBetween,
Text,
List,
Boolean,
DateTime,
DateTimeBetween
}
}
| zzgaminginc-pointofssale | Lib/DataGridFilterLibrary/Support/FilterType.cs | C# | gpl3 | 496 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
namespace DataGridFilterLibrary.Support
{
public class CheckBoxValueConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool result = false;
if (value != null && value.GetType() == typeof(String))
{
Boolean.TryParse(value.ToString(), out result);
}
else if (value != null)
{
result = System.Convert.ToBoolean(value);
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value;
}
#endregion
}
}
| zzgaminginc-pointofssale | Lib/DataGridFilterLibrary/Support/CheckBoxValueConverter.cs | C# | gpl3 | 985 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Resources;
using System.Collections;
using System.Reflection;
using System.Windows.Data;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Windows.Markup;
namespace DataGridFilterLibrary.Support
{
/// <summary>
/// Code from: http://www.ageektrapped.com/blog/the-missing-net-7-displaying-enums-in-wpf/
/// </summary>
[ContentProperty("OverriddenDisplayEntries")]
public class EnumDisplayer : IValueConverter
{
private Type type;
private IDictionary displayValues;
private IDictionary reverseValues;
private List<EnumDisplayEntry> overriddenDisplayEntries;
public EnumDisplayer()
{
}
public EnumDisplayer(Type type)
{
this.Type = type;
}
public Type Type
{
get { return type; }
set
{
if (!value.IsEnum)
throw new ArgumentException("parameter is not an Enumermated type", "value");
this.type = value;
}
}
public ReadOnlyCollection<string> DisplayNames
{
get
{
Type displayValuesType = typeof(Dictionary<,>).GetGenericTypeDefinition().MakeGenericType(type, typeof(string));
this.displayValues = (IDictionary)Activator.CreateInstance(displayValuesType);
this.reverseValues =
(IDictionary)Activator.CreateInstance(typeof(Dictionary<,>)
.GetGenericTypeDefinition()
.MakeGenericType(typeof(string), type));
var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static);
foreach (var field in fields)
{
DisplayStringAttribute[] a = (DisplayStringAttribute[])
field.GetCustomAttributes(typeof(DisplayStringAttribute), false);
string displayString = GetDisplayStringValue(a);
object enumValue = field.GetValue(null);
if (displayString == null)
{
displayString = GetBackupDisplayStringValue(enumValue);
}
if (displayString != null)
{
displayValues.Add(enumValue, displayString);
reverseValues.Add(displayString, enumValue);
}
}
return new List<string>((IEnumerable<string>)displayValues.Values).AsReadOnly();
}
}
private string GetDisplayStringValue(DisplayStringAttribute[] a)
{
if (a == null || a.Length == 0) return null;
DisplayStringAttribute dsa = a[0];
if (!string.IsNullOrEmpty(dsa.ResourceKey))
{
ResourceManager rm = new ResourceManager(type);
return rm.GetString(dsa.ResourceKey);
}
return dsa.Value;
}
private string GetBackupDisplayStringValue(object enumValue)
{
if (overriddenDisplayEntries != null && overriddenDisplayEntries.Count > 0)
{
EnumDisplayEntry foundEntry = overriddenDisplayEntries.Find(delegate(EnumDisplayEntry entry)
{
object e = Enum.Parse(type, entry.EnumValue);
return enumValue.Equals(e);
});
if (foundEntry != null)
{
if (foundEntry.ExcludeFromDisplay) return null;
return foundEntry.DisplayString;
}
}
return Enum.GetName(type, enumValue);
}
public List<EnumDisplayEntry> OverriddenDisplayEntries
{
get
{
if (overriddenDisplayEntries == null)
overriddenDisplayEntries = new List<EnumDisplayEntry>();
return overriddenDisplayEntries;
}
}
object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return displayValues[value];
}
object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return reverseValues[value];
}
}
public class EnumDisplayEntry
{
public string EnumValue { get; set; }
public string DisplayString { get; set; }
public bool ExcludeFromDisplay { get; set; }
}
}
| zzgaminginc-pointofssale | Lib/DataGridFilterLibrary/Support/EnumDisplayer.cs | C# | gpl3 | 4,898 |