Last active
December 20, 2015 06:48
-
-
Save JohanLarsson/6088121 to your computer and use it in GitHub Desktop.
Wpf Stuff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some stuff | |
git checkout my-branch | |
git rebase master | |
git checkout master | |
git merge my-branch |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[TestCase(typeof(Stats), "StatsProp")] | |
public void CreateListView(Type type, string bindingPopertyName) | |
{ | |
PropertyInfo[] propertyInfos = type.GetProperties(); | |
var listView = new XElement("ListView"); | |
listView.Add(new XAttribute("ItemsSource", string.Format(@"{{Binding {0}}}", bindingPopertyName))); | |
var view = new XElement("ListView.View"); | |
var gridView = new XElement("GridView"); | |
foreach (var propertyInfo in propertyInfos) | |
{ | |
var column = new XElement("GridViewColumn"); | |
column.Add(new XAttribute("Header", propertyInfo.Name)); | |
column.Add(new XAttribute("DisplayMemberBinding", string.Format(@"{{Binding {0}}}", propertyInfo.Name))); | |
gridView.Add(column); | |
} | |
view.Add(gridView); | |
listView.Add(view); | |
Console.Write(listView.ToString()); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Generates the Xaml for showing all properties of a class | |
/// </summary> | |
/// <param name="type"></param> | |
/// <param name="bindingPopertyName"></param> | |
[TestCase(typeof(Stats), "StatsProp")] | |
public void CreatePropertyGrid(Type type, string bindingPopertyName) | |
{ | |
PropertyInfo[] propertyInfos = type.GetProperties(); | |
var grid = new XElement("Grid"); | |
grid.Add(new XAttribute("DataContext", string.Format(@"{{Binding {0}}}", bindingPopertyName))); | |
var rows = new XElement("Grid.RowDefinitions"); | |
foreach (var propertyInfo in propertyInfos) | |
{ | |
var rowDef = new XElement("RowDefinition"); | |
rowDef.Add(new XAttribute("Height", @"Auto")); | |
rows.Add(rowDef); | |
} | |
grid.Add(rows); | |
var columns = new XElement("Grid.ColumnDefinitions"); | |
var col1 = new XElement("ColumnDefinition"); | |
col1.Add(new XAttribute("Width", "Auto")); | |
var col2 = new XElement("ColumnDefinition"); | |
columns.Add(col1); | |
columns.Add(col2); | |
grid.Add(columns); | |
for (int index = 0; index < propertyInfos.Length; index++) | |
{ | |
var propertyInfo = propertyInfos[index]; | |
var label = new XElement("Label", propertyInfo.Name); | |
label.Add(new XAttribute("Grid.Row", index.ToString())); | |
label.Add(new XAttribute("Grid.Column", 0.ToString())); | |
grid.Add(label); | |
var textBox = new XElement("TextBox"); | |
textBox.Add(new XAttribute("Grid.Row", index.ToString())); | |
textBox.Add(new XAttribute("Grid.Column", 1.ToString())); | |
textBox.Add(new XAttribute("Text", string.Format(@"{{Binding {0}}}", propertyInfo.Name))); | |
grid.Add(textBox); | |
} | |
Console.Write(grid.ToString()); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<Grid attachedProperties:Grid.Rows="50;50;*;*" | |
attachedProperties:Grid.Columns="50;50;*"> | |
<Rectangle attachedProperties:Grid.Cell="0 1" Fill="Blue"/> | |
<Rectangle attachedProperties:Grid.Cell="1 1" Fill="Red"/> | |
</Grid> | |
/// <summary> | |
/// http://samondotnet.blogspot.se/2012/03/wpf-grid-layout-simplified-using-rows.html | |
/// </summary> | |
public static class Grid | |
{ | |
private static readonly GridLengthConverter Converter = new GridLengthConverter(); | |
private static readonly char[] SplitSeparators = { ' ', ';' }; | |
internal static IEnumerable<GridLength> ToGridLengths(this object newValue) | |
{ | |
if (newValue == null) | |
return Enumerable.Empty<GridLength>(); | |
string[] strings = ((string)newValue).Split(SplitSeparators); | |
return strings.Select(Converter.ConvertFromString).Cast<GridLength>(); | |
} | |
public static string GetColumns(System.Windows.Controls.Grid grid) | |
{ | |
return (string)grid.GetValue(ColumnsProperty); | |
} | |
public static void SetColumns(System.Windows.Controls.Grid grid, string value) | |
{ | |
grid.SetValue(ColumnsProperty, value); | |
} | |
// Using a DependencyProperty as the backing store for Columns. This enables animation, styling, binding, etc... | |
public static readonly DependencyProperty ColumnsProperty = | |
DependencyProperty.RegisterAttached("Columns", typeof(string), typeof(Grid), | |
new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure, ColumnsUpdated)); | |
public static void ColumnsUpdated(DependencyObject d, DependencyPropertyChangedEventArgs e) | |
{ | |
if (Equals(e.NewValue, e.OldValue)) | |
return; | |
var grid = (System.Windows.Controls.Grid)d; | |
grid.ColumnDefinitions.Clear(); | |
foreach (var cd in e.NewValue.ToGridLengths() | |
.Select(x => new ColumnDefinition { Width = x })) | |
{ | |
grid.ColumnDefinitions.Add(cd); | |
} | |
} | |
public static string GetRows(System.Windows.Controls.Grid grid) | |
{ | |
return (string)grid.GetValue(RowsProperty); | |
} | |
public static void SetRows(System.Windows.Controls.Grid grid, string value) | |
{ | |
grid.SetValue(RowsProperty, value); | |
} | |
// Using a DependencyProperty as the backing store for Rows. This enables animation, styling, binding, etc... | |
public static readonly DependencyProperty RowsProperty = | |
DependencyProperty.RegisterAttached("Rows", typeof(string), typeof(Grid), | |
new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure, RowsUpdated)); | |
public static void RowsUpdated(DependencyObject d, DependencyPropertyChangedEventArgs e) | |
{ | |
if (Equals(e.NewValue, e.OldValue)) | |
return; | |
var grid = (System.Windows.Controls.Grid)d; | |
grid.RowDefinitions.Clear(); | |
foreach (var rd in e.NewValue.ToGridLengths() | |
.Select(x => new RowDefinition() { Height = x })) | |
{ | |
grid.RowDefinitions.Add(rd); | |
} | |
} | |
public static string GetCell(UIElement obj) | |
{ | |
return (string)obj.GetValue(CellProperty); | |
} | |
public static void SetCell(UIElement obj, string value) | |
{ | |
obj.SetValue(CellProperty, value); | |
} | |
public static readonly DependencyProperty CellProperty = | |
DependencyProperty.RegisterAttached("Cell", typeof(string), typeof(Grid), | |
new FrameworkPropertyMetadata("0 0", FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure, CellUpdated)); | |
public static void CellUpdated(DependencyObject d, DependencyPropertyChangedEventArgs e) | |
{ | |
if (string.Equals(e.OldValue, e.NewValue)) | |
return; | |
var element = (UIElement)d; | |
// var grid = (System.Windows.Controls.Grid)element.VisualAncestors().OfType<System.Windows.Controls.Panel>().First(); | |
var rowAndColumn = ((string)e.NewValue).Split(SplitSeparators); | |
var row = int.Parse(rowAndColumn[0]); | |
var column = int.Parse(rowAndColumn[1]); | |
// if (row >= grid.RowDefinitions.Count) | |
// throw new FormatException("Grid.Row cannot be > RowDefinitions.Count"); | |
// if (column >= grid.ColumnDefinitions.Count) | |
// throw new FormatException("Grid.Colunn cannot be > ColumnDefinitions.Count"); | |
System.Windows.Controls.Grid.SetRow(element, row); | |
System.Windows.Controls.Grid.SetColumn(element, column); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//<Window.Resources> | |
// <local:RelativeToAbsolutePathConverter x:Key="relToAbsPathConverter" /> | |
// <DataTemplate x:Key="stringTemplate"> | |
// <TextBlock Text="{Binding}"/> | |
// </DataTemplate> | |
// <DataTemplate x:Key="imageTemplate"> | |
// <Image Source="{Binding Converter={StaticResource relToAbsPathConverter}}" | |
// Stretch="UniformToFill" Width="200"/> | |
// </DataTemplate> | |
// <local:ImgStringTemplateSelector | |
// ImageTemplate="{StaticResource imageTemplate}" | |
// StringTemplate="{StaticResource stringTemplate}" | |
// x:Key="imgStringTemplateSelector" /> | |
//</Window.Resources> | |
/// <summary> | |
/// http://tech.pro/tutorial/807/wpf-tutorial-how-to-use-a-datatemplateselector | |
/// </summary> | |
public class ImgStringTemplateSelector : DataTemplateSelector | |
{ | |
public DataTemplate ImageTemplate { get; set; } | |
public DataTemplate StringTemplate { get; set; } | |
public override DataTemplate SelectTemplate(object item, | |
DependencyObject container) | |
{ | |
String path = (string)item; | |
String ext = System.IO.Path.GetExtension(path); | |
if (System.IO.File.Exists(path) && ext == ".jpg") | |
return ImageTemplate; | |
return StringTemplate; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MultiplyConverter : IValueConverter | |
{ | |
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) | |
{ | |
var d = System.Convert.ToDouble(value); | |
double p = System.Convert.ToDouble(parameter,CultureInfo.InvariantCulture); | |
return d * p; | |
} | |
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) | |
{ | |
throw new NotImplementedException(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Bookmarks.CollectionChanged += (sender, e) => | |
{ | |
if (e.OldItems != null) | |
{ | |
foreach (INotifyPropertyChanged item in e.OldItems) | |
item.PropertyChanged -= SetDirty; | |
} | |
if (e.NewItems != null) | |
foreach (INotifyPropertyChanged item in e.NewItems) | |
item.PropertyChanged += SetDirty; | |
IsBookmarksDirty = true; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class OcExt | |
{ | |
public static void InvokeAdd<T>(this ObservableCollection<T> collection, T newItem) | |
{ | |
collection.Invoke(()=>collection.Add(newItem)); | |
} | |
public static void InvokeRemove<T>(this ObservableCollection<T> collection, T oldItem) | |
{ | |
collection.Invoke(() => collection.Remove(oldItem)); | |
} | |
public static DispatcherOperation AddAsync<T>(this ObservableCollection<T> collection, T newItem) | |
{ | |
return collection.InvokeAsync(() => collection.Add(newItem)); | |
} | |
public static DispatcherOperation AddRangeAsync<T>(this ObservableCollection<T> collection, IEnumerable<T> newItems) | |
{ | |
return collection.InvokeAsync(() => | |
{ | |
foreach (var newItem in newItems) | |
{ | |
collection.Add(newItem); | |
} | |
}); | |
} | |
public static void AddRange<T>(this ObservableCollection<T> collection, IEnumerable<T> newItems) | |
{ | |
collection.Invoke(() => | |
{ | |
foreach (var newItem in newItems) | |
{ | |
collection.Add(newItem); | |
} | |
}); | |
} | |
public static DispatcherOperation RemoveAsync<T>(this ObservableCollection<T> collection, T oldItem) | |
{ | |
return collection.InvokeAsync(() => collection.Remove(oldItem)); | |
} | |
public static DispatcherOperation InvokeAsync<T>(this ObservableCollection<T> col, Action action) | |
{ | |
Dispatcher dispatcher = Application.Current != null | |
? Application.Current.Dispatcher | |
: Dispatcher.CurrentDispatcher; | |
return dispatcher.InvokeAsync(action); | |
} | |
public static void Invoke<T>(this ObservableCollection<T> col, Action action) | |
{ | |
Dispatcher dispatcher = Application.Current != null | |
? Application.Current.Dispatcher | |
: Dispatcher.CurrentDispatcher; | |
dispatcher.Invoke(action); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class ReactiveExt | |
{ | |
public static IObservable<TProperty> ToObservable<TNotifier, TProperty>(this TNotifier source, | |
Expression<Func<TNotifier, TProperty>> property) where TNotifier : INotifyPropertyChanged | |
{ | |
string name = ((MemberExpression)property.Body).Member.Name; | |
Func<TNotifier, TProperty> getter = property.Compile(); | |
IObservable<TProperty> observable = source.ToObservable() | |
.Select(x=>x.EventArgs) | |
.Where(x => x.PropertyName == name) | |
.Select(x => getter(source)); | |
return observable; | |
} | |
public static IObservable<EventPattern<PropertyChangedEventArgs>> ToObservable(this INotifyPropertyChanged source) | |
{ | |
IObservable<EventPattern<PropertyChangedEventArgs>> observable = Observable.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>( | |
x => source.PropertyChanged += x, | |
x => source.PropertyChanged -= x); | |
return observable; | |
} | |
public static IObservable<TProperty> ToObservable<TNotifier, TProperty>(this OcNpcListener<TNotifier> source, | |
Expression<Func<TNotifier, TProperty>> property) where TNotifier : INotifyPropertyChanged | |
{ | |
string name = ((MemberExpression)property.Body).Member.Name; | |
Func<TNotifier, TProperty> getter = property.Compile(); | |
IObservable<TProperty> observable = source.ToObservable() | |
.Select(x => x.EventArgs) | |
.Where(x => x.PropertyName == name) | |
.Select(x => getter((TNotifier)x.Child)); | |
return observable; | |
} | |
public static IObservable<EventPattern<ChildPropertyChangedEventArgs>> ToObservable<T>(this OcNpcListener<T> source) where T : INotifyPropertyChanged | |
{ | |
IObservable<EventPattern<ChildPropertyChangedEventArgs>> observable = Observable | |
.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>( | |
x => source.PropertyChanged += x, | |
x => source.PropertyChanged -= x) | |
.Select(x=>new EventPattern<ChildPropertyChangedEventArgs>(x.Sender,(ChildPropertyChangedEventArgs)x.EventArgs)); | |
return observable; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class RelayCommandBase : ICommand | |
{ | |
private readonly Action<object> _action; | |
private readonly Predicate<object> _condition; | |
protected RelayCommandBase(Action<object> action, Predicate<object> condition) | |
:this(action) | |
{ | |
_condition = condition ?? (o => true); | |
} | |
protected RelayCommandBase(Action<object> action) | |
{ | |
if (action == null) | |
throw new ArgumentNullException("action"); | |
_action = action; | |
_condition = (o) => true; | |
} | |
public abstract event EventHandler CanExecuteChanged; | |
public bool CanExecute(object parameter) | |
{ | |
return _condition(parameter); | |
} | |
public void Execute(object parameter) | |
{ | |
_action(parameter); | |
} | |
} | |
public class RelayCommand : RelayCommandBase | |
{ | |
public RelayCommand(Action<object> action, Predicate<object> condition) : base(action, condition) | |
{ | |
} | |
public RelayCommand(Action<object> action) : base(action) | |
{ | |
} | |
/// <summary> | |
/// http://stackoverflow.com/a/2588145/1069200 | |
/// </summary> | |
public override event EventHandler CanExecuteChanged | |
{ | |
add { CommandManager.RequerySuggested += value; } | |
remove { CommandManager.RequerySuggested -= value; } | |
} | |
} | |
public class ManualRelayCommand : RelayCommandBase | |
{ | |
private readonly bool _raiseCanExecuteOnDispatcher; | |
public ManualRelayCommand(Action<object> action, Predicate<object> condition, bool raiseCanExecuteOnDispatcher = true) | |
: base(action, condition) | |
{ | |
_raiseCanExecuteOnDispatcher = raiseCanExecuteOnDispatcher; | |
} | |
public ManualRelayCommand(Action<object> action, bool raiseCanExecuteOnDispatcher = true) | |
: base(action) | |
{ | |
_raiseCanExecuteOnDispatcher = raiseCanExecuteOnDispatcher; | |
} | |
public override event EventHandler CanExecuteChanged | |
{ | |
add | |
{ | |
InternalCanExecuteChangedEventManager.AddHandler(this, value); | |
} | |
remove | |
{ | |
InternalCanExecuteChangedEventManager.RemoveHandler(this, value); | |
} | |
} | |
private event EventHandler InternalCanExecuteChanged; | |
public void RaiseCanExecuteChanged() | |
{ | |
EventHandler handler = InternalCanExecuteChanged; | |
if (handler != null) | |
{ | |
if (_raiseCanExecuteOnDispatcher) | |
{ | |
Application.Current.Dispatcher.BeginInvoke(new Action(() => handler(this, new EventArgs()))); | |
} | |
else | |
{ | |
handler(this, new EventArgs()); | |
} | |
} | |
} | |
private class InternalCanExecuteChangedEventManager : WeakEventManager | |
{ | |
private static readonly InternalCanExecuteChangedEventManager Manager = new InternalCanExecuteChangedEventManager(); | |
static InternalCanExecuteChangedEventManager() | |
{ | |
SetCurrentManager(typeof(InternalCanExecuteChangedEventManager), Manager); | |
} | |
internal static void AddHandler(ManualRelayCommand source, EventHandler handler) | |
{ | |
Manager.ProtectedAddHandler(source, handler); | |
} | |
internal static void RemoveHandler(ManualRelayCommand source, EventHandler handler) | |
{ | |
Manager.ProtectedRemoveHandler(source, handler); | |
} | |
////protected override ListenerList NewListenerList() | |
////{ | |
//// return new ListenerList(); | |
////} | |
protected override void StartListening(object source) | |
{ | |
((ManualRelayCommand)source).InternalCanExecuteChanged += DeliverEvent; | |
} | |
protected override void StopListening(object source) | |
{ | |
((ManualRelayCommand)source).InternalCanExecuteChanged -= DeliverEvent; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// http://stackoverflow.com/questions/94456/load-a-wpf-bitmapimage-from-a-system-drawing-bitmap | |
/// </summary> | |
/// <param name="icon"></param> | |
/// <returns></returns> | |
private BitmapImage ToBitmapImage(Icon icon) | |
{ | |
using (MemoryStream memory = new MemoryStream()) | |
{ | |
icon.Save(memory); | |
memory.Position = 0; | |
BitmapImage bitmapImage = new BitmapImage(); | |
bitmapImage.BeginInit(); | |
bitmapImage.StreamSource = memory; | |
bitmapImage.CacheOption = BitmapCacheOption.OnLoad; | |
bitmapImage.EndInit(); | |
return bitmapImage; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TreeViewChildrenConverter :IValueConverter | |
{ | |
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) | |
{ | |
var treeView = (TreeView) value; | |
var allItemContainers = GetAllItemContainers(treeView); | |
return allItemContainers.Select(x => x.DataContext); | |
} | |
private IEnumerable<TreeViewItem> GetAllItemContainers(ItemsControl itemsControl) | |
{ | |
for (int i = 0; i < itemsControl.Items.Count; i++) | |
{ | |
// try to get the item Container | |
var containerFromIndex = itemsControl.ItemContainerGenerator.ContainerFromIndex(i); | |
TreeViewItem childItemContainer = containerFromIndex as TreeViewItem; | |
// the item container maybe null if it is still not generated from the runtime | |
if (childItemContainer != null) | |
{ | |
yield return childItemContainer; | |
if (childItemContainer.IsExpanded) | |
{ | |
foreach (var treeViewItem in GetAllItemContainers(childItemContainer)) | |
{ | |
yield return treeViewItem; | |
} | |
} | |
} | |
} | |
} | |
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) | |
{ | |
throw new NotImplementedException(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment