Files
spark/src/client/spark/view/Extensions/WPFExtensions.cs
T

379 lines
16 KiB
C#

using bts;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
namespace mbts.ui {
static class WPFExtensions {
public static object get_template_child(this Control control, string name) {
if (control == null) throw new ArgumentNullException(nameof(control));
return control?.Template?.FindName(name, control);
}
public static T get_template_child<T>(this Control control, string name) {
object obj = get_template_child(control, name);
return ConvertUtils.try_convert<T>(obj);
}
public static bool try_get_template_child(this Control control, string name, out object result) {
if (control == null) throw new ArgumentNullException(nameof(control));
var t = control.Template;
if (t != null) {
result = control.Template.FindName(name, control);
return result != null;
}
result = null;
return false;
}
public static bool try_get_template_child<T>(this Control control, string name, out T result) {
if (try_get_template_child(control, name, out object obj))
return ConvertUtils.try_convert(obj, out result);
result = default;
return false;
}
public static object assert_template_child(this Control control, string name) {
if (!try_get_template_child(control, name, out object result))
throw new InvalidOperationException($"Template must have a child named '{name}'");
return result;
}
public static T assert_template_child<T>(this Control control, string name) {
if (!try_get_template_child(control, name, out T result))
throw new InvalidOperationException($"Template must have a {typeof(T)} child named '{name}'");
return result;
}
public static IEnumerable<DependencyObject> visual_children(this FrameworkElement v) {
var count = VisualTreeHelper.GetChildrenCount(v);
for (var x = 0; x < count; x++) {
yield return VisualTreeHelper.GetChild(v, x);
}
}
public static Color rgb_color(this UInt32 color) {
var bytes = BitConverter.GetBytes(color);
return Color.FromRgb(bytes[2], bytes[1], bytes[0]);
}
public static SolidColorBrush to_brush(this BTSColor color) =>
new SolidColorBrush(color);
public static Brush rgb_brush(this uint color) {
var brush = new SolidColorBrush(rgb_color(color));
brush.Freeze();
return brush;
}
public static SolidColorBrush rgb_solid_brush(this uint color) =>
new SolidColorBrush(rgb_color(color));
public static UInt32 rgb_color(this Color color) {
return (uint)color.A << 24 | (uint)color.R << 16 | (uint)color.G << 8 | (uint)color.B;
}
public static Brush to_brush(this Color color) =>
new SolidColorBrush(color);
public static SolidColorBrush to_solid_brush(this Color color) =>
new SolidColorBrush(color);
public static Brush frozen(this Brush brush) {
brush.Freeze();
return brush;
}
public static SolidColorBrush frozen(this SolidColorBrush brush) {
brush.Freeze();
return brush;
}
public static SolidColorBrush with(this SolidColorBrush brush, double opacity) {
brush.Opacity = opacity;
return brush;
}
public static Pen frozen(this Pen pen) {
pen.Freeze();
return pen;
}
public static ImageSource frozen(this ImageSource image_source) {
image_source.Freeze();
return image_source;
}
// Perform a breadth first traversal of all children returning any that match the predicate.
// Matching children are *not* further traversed
public static IEnumerable<FrameworkElement> visual_children_where(this FrameworkElement v, Func<FrameworkElement, bool> match) {
var children = visual_children(v).OfType<FrameworkElement>().ToList();
while(children.Count() > 0) {
var next = new List<FrameworkElement>();
foreach (var c in children) {
if (match(c)) {
yield return c;
}
else {
next.AddRange(visual_children(c).OfType<FrameworkElement>());
}
}
children = next;
}
}
public static IEnumerable<T> descendants_of_type<T>(this FrameworkElement v) {
return v.visual_children_where(fe => fe is T).Cast<T>();
}
public static T find_ancestor_of_type<T>(this FrameworkElement element) where T : DependencyObject {
if (element.Parent is T)
return (T)element.Parent;
else if (element.TemplatedParent is T)
return (T)element.TemplatedParent;
else {
FrameworkElement logical_parent = VisualTreeHelper.GetParent(element) as FrameworkElement;
if (logical_parent != null) {
var rv = logical_parent.find_ancestor_of_type<T>();
if (rv is T)
return (T)rv;
}
FrameworkContentElement content_parent = VisualTreeHelper.GetParent(element) as FrameworkContentElement;
if (content_parent != null) {
var rv = content_parent.find_ancestor_of_type<T>();
if (rv is T)
return (T)rv;
}
if (element.Parent is FrameworkElement) {
var rv = ((FrameworkElement)element.Parent).find_ancestor_of_type<T>();
if (rv is T)
return (T)rv;
} else if (element.Parent is FrameworkContentElement) {
var rv = ((FrameworkContentElement)element.Parent).find_ancestor_of_type<T>();
if (rv is T)
return (T)rv;
}
if (element.TemplatedParent is FrameworkElement) {
var rv = ((FrameworkElement)element.TemplatedParent).find_ancestor_of_type<T>();
if (rv is T)
return (T)rv;
} else if (element.TemplatedParent is FrameworkContentElement) {
var rv = ((FrameworkContentElement)element.TemplatedParent).find_ancestor_of_type<T>();
if (rv is T)
return (T)rv;
}
}
return default(T);
}
public static T find_ancestor_of_type<T>(this FrameworkContentElement element) where T : DependencyObject {
if (element.Parent is T)
return (T)element.Parent;
else if (element.TemplatedParent is T)
return (T)element.TemplatedParent;
else {
if (element.Parent is FrameworkElement) {
var rv = ((FrameworkElement)element.Parent).find_ancestor_of_type<T>();
if (rv is T)
return (T)rv;
} else if (element.Parent is FrameworkContentElement) {
var rv = ((FrameworkContentElement)element.Parent).find_ancestor_of_type<T>();
if (rv is T)
return (T)rv;
}
if (element.TemplatedParent is FrameworkElement) {
var rv = ((FrameworkElement)element.TemplatedParent).find_ancestor_of_type<T>();
if (rv is T)
return (T)rv;
}
if (element.TemplatedParent is FrameworkContentElement) {
var rv = ((FrameworkContentElement)element.TemplatedParent).find_ancestor_of_type<T>();
if (rv is T)
return (T)rv;
}
}
return default(T);
}
public static void clear_bindings(this DependencyObject d_obj, params DependencyProperty[] d_props) {
foreach (var dp in d_props)
BindingOperations.ClearBinding(d_obj, dp);
}
public static IDisposable attach_binding(this DependencyObject target, DependencyProperty target_property, string path, FrameworkElement source_view) {
object source_vm = source_view.DataContext;
try_reset_binding();
source_view.DataContextChanged += on_data_context_changed;
return Disposable.Create(() => {
try {
source_view.DataContextChanged -= on_data_context_changed;
} catch (Exception ex) {
Log.Ui.warn($"Error detaching from {nameof(source_view)}.{nameof(FrameworkElement.DataContextChanged)} event: {ex}.");
}
});
void on_data_context_changed(object sender, DependencyPropertyChangedEventArgs e) {
source_vm = e.NewValue;
try_reset_binding();
}
void try_reset_binding() {
if (source_vm != null)
target.reset_binding(target_property, new Binding(path) { Source = source_vm });
}
}
public static void reset_binding(this DependencyObject target, DependencyProperty target_property, BindingBase binding) {
BindingOperations.ClearBinding(target, target_property);
BindingOperations.SetBinding(target, target_property, binding);
}
public static void TryRaiseCanExecuteChanged(this ICommand command) {
if (command == null) return;
else if (command is IRaiseCanExecuteChangedCommand temp)
temp.RaiseCanExecuteChanged();
else
throw new NotImplementedException("This ICommand does not implement IRaiseCanExecuteChanged");
}
public static async Task ExecuteAsync(this ICommand command, object parameter) {
ExceptionAssert.Argument.NotNull(command, nameof(command));
if (command is IAsyncCommand acmd)
await acmd.Execute(parameter);
else
await Task.Run(() => command.Execute(parameter));
}
public static void TryExecuteIfCan(this ICommand command, object parameter) {
if (command != null)
ExecuteIfCan(command, parameter);
}
public static void ExecuteIfCan(this ICommand command, object parameter) {
ExceptionAssert.Argument.NotNull(command, nameof(command));
if (command.CanExecute(parameter))
command.Execute(parameter);
}
public static IDisposable ObserveProperty(this DependencyObject instance, DependencyProperty property, EventHandler callback) {
var descriptor = DependencyPropertyDescriptor.FromProperty(property, instance.GetType());
if (descriptor != null) {
descriptor.AddValueChanged(instance, callback);
return Disposable.Create(() => descriptor.RemoveValueChanged(instance, callback));
}
throw new ArgumentException("Could not find property descriptor given type");
}
public static IObservable<T> Observe<T>(this DependencyObject instance, DependencyProperty property) {
Log.assert(typeof(T) == instance.GetType());
return Observable.Create<T>(observer => {
return instance.ObserveProperty(property, (o, e) => {
observer.OnNext((T)instance.GetValue(property));
});
});
}
public static void CommitAny(this IEditableCollectionView collection) {
if (collection.IsEditingItem) {
collection.CommitEdit();
} else if (collection.IsAddingNew) {
collection.CommitNew();
}
}
public static void CancelAny(this IEditableCollectionView collection) {
if (collection.IsEditingItem) {
if (collection.CanCancelEdit)
collection.CancelEdit();
} else if (collection.IsAddingNew) {
collection.CancelNew();
}
}
public static void ClearMouseBindings(this UIElement element, MouseAction action) =>
ClearMouseBindings(element, action, ModifierKeys.None);
public static void ClearMouseBindings(this UIElement element, MouseAction action, ModifierKeys modifiers) {
for (int i = 0; i < element.InputBindings.Count; i++) {
var mb = element.InputBindings[i] as MouseBinding;
if (mb != null) {
var g = mb.Gesture as MouseGesture;
if (g != null && g.MouseAction == action && g.Modifiers == modifiers)
element.InputBindings.RemoveAt(i);
}
}
}
public static void ClearKeyBindings(this UIElement element, Key key) =>
ClearKeyBindings(element, key, ModifierKeys.None);
public static void ClearKeyBindings(this UIElement element, Key key, ModifierKeys modifiers) {
for (int i = 0; i < element.InputBindings.Count; i++) {
if (element.InputBindings[i] is KeyBinding kb && kb.Key == key && kb.Modifiers == modifiers)
element.InputBindings.RemoveAt(i--);
}
}
public static void ClearCommandBindings(this UIElement element, RoutedCommand cmd) {
for (int i = 0; i < element.CommandBindings.Count; i++) {
if (element.CommandBindings[i].Command == cmd)
element.CommandBindings.RemoveAt(i--);
}
}
public static void EnsureIsVisible(this Window window) {
if (!window.IsVisible) window.Show();
if (window.WindowState == WindowState.Minimized) {
window.WindowState = WindowState.Normal;
}
window.ensure_onscreen();
window.Activate();
}
public static Size MeasureText(this Typeface font, double size, string text) {
#pragma warning disable CS0618 // Type or member is obsolete
var ft = new FormattedText(text, System.Globalization.CultureInfo.CurrentCulture, System.Windows.FlowDirection.LeftToRight, font, size, Brushes.Black);
#pragma warning restore CS0618 // Type or member is obsolete
return new Size(ft.Width, ft.Height);
}
public static void SetSortingCriteria(this ICollectionView collection_view, IEnumerable<SortingCriteria> sorting_criteria) {
collection_view.SortDescriptions.Clear();
if (sorting_criteria != null)
foreach (var sc in sorting_criteria)
collection_view.SortDescriptions.Add(new SortDescription(sc.col_name, sc.is_ascending ? ListSortDirection.Ascending : ListSortDirection.Descending));
}
/// <summary>
/// Converts <paramref name="collection_view"/>.SortDescriptions into a List&lt;<see cref="SortingCriteria"/>&gt;.
/// </summary>
public static List<SortingCriteria> get_sorting_criteria(this ICollectionView collection_view, ObservableCollection<controls.DIYGrid.ColumnBase> columns) =>
collection_view.SortDescriptions
.Select(sd => new SortingCriteria(columns.FirstOrDefault(c => c.sort_member_path == sd.PropertyName)?.id, sd.Direction == ListSortDirection.Ascending))
.Where(sc => sc.col_name != null)
.ToList();
/// <summary>
/// Converts each <see cref="SortingCriteria"/> into a <see cref="SortDescription"/> and assigns the result to <paramref name="collection_view"/>.SortDescriptions.
/// </summary>
public static void set_sort_descriptions(this ICollectionView collection_view, IEnumerable<SortingCriteria> sorting_criterion, ObservableCollection<controls.DIYGrid.ColumnBase> columns) {
using (collection_view.DeferRefresh()) {
collection_view.SortDescriptions.SetItems(sorting_criterion.empty_if_null()
.Select(sc => new SortDescription(
columns.FirstOrDefault(c => string.Equals(c.id, sc.col_name, StringComparison.CurrentCultureIgnoreCase))?.sort_member_path,
sc.is_ascending ? ListSortDirection.Ascending : ListSortDirection.Descending))
.Where(sd => !string.IsNullOrEmpty(sd.PropertyName)));
}
}
}
}