10 UWP snippets for visual studio you cannot live without

Do you want to speed up writing code for Universal Windows Projects? Code snippets help you to write code by doing the typing for you. Here’s a selection of the ones that I use the most

Download the snippets from github and copy them to

c:\Users\maxzorin\Documents\Visual Studio 15\Code Snippets\Visual C#\My Code Snippets\

where you replace maxzorin with your name and Visual Studio 15 with your version of Visual Studio

clsBehavior

[TypeConstraint(typeof(ListViewBase))]
public class SelectAfterRemoveBehavior : DependencyObject, IBehavior
{
    private ListViewBase _associatedObject;

    public DependencyObject AssociatedObject
    {
        get { return _associatedObject; }
    }

    public void Attach(DependencyObject associatedObject)
    {
        _associatedObject = (ListViewBase)associatedObject;
    }

    public void Detach()
    {
        // dispose stuff
    }
}

clsDelegateCommand

Since x:Bind can bind to public methods, a DelegateCommand is not needed as much as it used to be. But if a XAML Button needs to be enabled/disabled depending on some ViewModel state, this DelegateCommand is your friend.

public class DelegateCommand<T> : ICommand
{
    public event EventHandler CanExecuteChanged;

    private readonly Predicate<T> _canExecute;
    private readonly Action<T> _executeAction;

    public DelegateCommand(Action<T> executeAction)
    {
        _executeAction = executeAction;
    }

    public DelegateCommand(Action<T> executeAction, Predicate<T> canExecute)
        : this(executeAction)
    {
        _canExecute = canExecute;
    }

    public bool CanExecute(T parameter)
    {
        if (_canExecute != null)
        {
            return _canExecute(parameter);
        }
        return true;
    }

    public void Execute(T parameter)
    {
        if (_executeAction != null)
        {
            _executeAction(parameter);
        }

        if (CanExecuteChanged != null)
        {
            CanExecuteChanged(this, EventArgs.Empty);
        }
    }

    public void RaiseCanExecuteChanged()
    {
        OnCanExecuteChanged();
    }

    protected virtual void OnCanExecuteChanged()
    {
        EventHandler handler = CanExecuteChanged;
        if (handler != null)
        {
            handler(this, EventArgs.Empty);
        }
    }

    bool ICommand.CanExecute(object parameter)
    {
        return CanExecute((T)parameter);
    }

    void ICommand.Execute(object parameter)
    {
        Execute((T)parameter);
    }
}

clsObservableObject

public class ObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void NotifyOfPropertyChange(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

equals_and_hash

public override bool Equals(object obj)
{
    if (ReferenceEquals(null, obj)) return false;
    if (ReferenceEquals(this, obj)) return true;
    if (obj.GetType() != this.GetType()) return false;
    return GetHashCode() == ((object)obj).GetHashCode();
}

public override int GetHashCode()
{
    // single value:
    // return _x.GetHashCode();

    // multiple values:
    // int hash = 0;
    // hash ^= _x.GetHashCode();
    // hash ^= _y.GetHashCode();
    // hash ^= (_z.!= null ? _z.zzz.GetHashCode() : 0);
    // return hash;
}

event

public event EventHandler NounVerbed; // NounVerbed?.Invoke(this, EventArgs.Empty);

loremIpsum

var loremIpsum = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam placerat pellentesque dolor. Maecenas dui ipsum, lacinia eget, dapibus non, vehicula a, urna. Pellentesque odio. Vivamus semper ipsum vel justo. Phasellus hendrerit mattis arcu. Nulla commodo, augue eget convallis euismod, diam sapien mollis enim, aliquet placerat urna orci sed libero. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aenean in eros usce ultricies libero ac arcu. Donec sodales diam a arcu. Maecenas non erat."

propNotify

private int myVar;
public int MyProperty
{
    get { return myVar; }
    set
    {
        if (myVar != value)
        {
            myVar = value;
            NotifyOfPropertyChange(nameof(MyProperty));
        }
    }
}

propas (attached property)

public static string GetName(DependencyObject obj)
{
    return (string)obj.GetValue(NameProperty);
}

public static void SetName(DependencyObject obj, string value)
{
    obj.SetValue(NameProperty, value);
}

public static readonly DependencyProperty NameProperty = DependencyProperty.RegisterAttached("Name", typeof(string), typeof(Employee), new PropertyMetadata(null, OnNameChanged));

private static void OnNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var source = d as FrameworkElement;
    if (source != null)
    {
        var value = (string)e.NewValue;
        //TODO: Handle new value.
    }
}

propds (dependency property with callback)

public string Text
{
    get { return (string)GetValue(TextProperty); }
    set { SetValue(TextProperty, value); }
}

public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(Employee), new PropertyMetadata(null, OnTextPropertyChanged));

private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var source = (Employee)d;

    var oldValue = e.OldValue as string;
    if (oldValue != null)
    {
        // dispose previous subcriptions like events
    }

    var newValue = (string)e.NewValue;
    // handle newValue
}

propds_nocallback (dependency property without callback)

public string Name
{
    get { return (string)GetValue(NameProperty); }
    set { SetValue(NameProperty, value); }
}

public static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(Employee), new PropertyMetadata(null));