That Conference 2017 – React Native: The Good Parts

That Conference 2017, Kalahari Resort, Lake Delton, WI
React Native: The Good Parts – Stan Bershadskiy

Day 1, 7 Aug 2017

Disclaimer: This post contains my own thoughts and notes based on attending That Conference 2017 presentations. Some content maps directly to what was originally presented. Other content is paraphrased or represents my own thoughts and opinions and should not be construed as reflecting the opinion of the speakers.

Executive Summary

  • Native app is a very different experience than web app
  • You get way better performance with native app
  • You get better development experience when working in React
  • React Native gives you best of both worlds–good development experience and best performance


Stan Bershadskiy

  • Architect at Modus Create
  • Author of React Native Cookbook
  • Working with React Native >1.5 yrs


React Native Cookbook

  • From UI to deployment
  • Not just “how”, but “why”


Modus

  • Product Studio
    • Consulting company
    • Specializing in mobile and web apps
    • Globally distributed agile teams
  • Community leaders
    • Published authors and conference speakers
    • Partners with GitHub et al


Mobile Apps Today

  • Split into three groups
    • Native
      • Excellent performance, slow development
    • Web/Hybrid – PhoneGap, Cordoba, Ionic
      • Easy development, terrible performance
      • HTML5/JS is not the solution for fast native apps
    • Cross Compiled – Xamarin, Titanium
      • Meh, dinosaur
      • Most people moving away from this world

We want, of course, good performance, quick development


React Native

  • A framework for building native mobile apps using JavaScript
  • JavaScript runs in interpreter on the platform
  • Different from cross-compiled, which compiles down to native


React’s Core Dependency

  • React.js


React.js

  • Parts
    • JSX – Describe the UI
    • Virtual DOM – Efficiently batch and schedule rendering
    • Lifecycle – Control how components render


How Does React Work?

  • View Declaration (JSX) -> Virtual DOM -> Target Platform
  • Initial phase – componentWillMount, render, componentDidMount
  • Update phase – shouldComponentUpdate, render, componentDidUpdate


React’s New Core Algorithm

  • Fiber – will also be in React Native (next version)


React Native

  • Parts
    • React – declarative goodness
    • Bridge – communication between JavaScript and native threads
    • Native UI SDK – Render Native UI elements on the main thread


How Does React Native Work?

  • JavaScript thread
    • Has event loop (60 fps)
    • JS Call – delegates to main thread, which does Native Call
  • Main thread
    • Renders to the UI
    • Main thread is never blocked, so UI responsive


The Good Parts


Layout System

  • Yoga
  • Flexbox and Absolute positioned layout system written in C++ to achieve maximum performance
  • Some parts written in assembly
  • Similar to web standards


Animated API

  • 60 fps goodness
  • Create Animated Values of a type that wrap components
  • Values can be composed in parallel, sequence or other variations
  • Animations can be executed on the native thread for increased performance
  • Native thread can kick off sub-thread on which to do the animation calculations. So UI isn’t blocked


Animated API Examples

  • React-Native-Foldview
  • Twitter Exploding Hearts
  • Can now export Adobe (something) Effects into React Native


Native Module Bridge

  • Native Made Easy
  • Easily expose native functionality and native UI components to be used by React Native


It’s Just JavaScript

  • Answer to anything is probably on Stack Overflow
  • All your business logic likely going to be implemented in JavaScript


Commonly Used JS Modules

  • Redux – state container
  • Lodash – looping
  • Moment – simple date manipulation


Community

  • This is the most important thing
  • Facebook and the Community as a whole work hand in hand to further the development of React native.
  • >50% of commits come from the community


Community Contributions

  • Expo(nent) – app development platform
  • React Navigation – navigation made simple (finally)
  • RNPM – Simple linking of native modules


The Not-So-Good Parts


Upgrading

  • “Hope you like reading diffs”
  • But it’s not critical that you upgrade immediately
  • If you’re actively developing, you could keep up with latest versions
  • But if further into lifecycle, don’t need to upgrade constantly


Android

  • Dealing with Native Android code is no fun
  • Device and version fragmentation cripples the development experience
  • Tons of devices, tons of Android versions
  • “Tread lightly”
  • Suggested starting with Android first, since once it works there, you know it will work on iOS


Development Mode

  • Apps work much slower in development mode, especially Android
  • But much faster in production mode


Where does React Native Belong?

  • Target platforms
    • iOS
    • Android
    • Apple TV
  • More
    • Universal Windows Platform – Surface tablets, Xbox One
    • Mac OS
    • Linux
  • Few more
    • Virtual Reality – Oculus (React VR)
    • Web – but Stan doesn’t recommend it
    • Other–just needs to run JavaScript interpreter in C++


React Native in the Wild

  • Skype
  • AirBnb
  • Instagram – recently switched over to React Native – claimed better velocity


Building Your Next App


Resources

  • Stan’s book
  • React Native Docs
  • GitHub issues page


Create React Native App

  • Simple platform-independent way to get up and running
  • Can push updates to your app while in production (if JavaScript)
    • e.g. Microsoft CodePush


Standard Way

  • Start with native IDE
    • Xcode
    • Android Studio
    • javaScript IDE
  • Still need to know how to go through deployment cycle on each platform


Best Practices

  • Render() – keep as lean as possible
  • Bridge – be mindful of data you send across bridge
    • Bridge has to serialize the types, so be careful of large blobs of data going across
    • To do complicated data manipulation, e.g. transfer megabytes, do this on the native side


First Use of React Native in Production

  • Facebook Groups
  • Ads Manager 2nd
Advertisements

That Conference 2017 – Intro to Docker

That Conference 2017, Kalahari Resort, Lake Delton, WI
Intro to Docker – John Ptacek

Day 1, 7 Aug 2017

Disclaimer: This post contains my own thoughts and notes based on attending That Conference 2017 presentations. Some content maps directly to what was originally presented. Other content is paraphrased or represents my own thoughts and opinions and should not be construed as reflecting the opinion of the speakers.

Executive Summary

  • Docker containers make deploying a running application easier and more repeatable
  • Tooling exists to deploy to Azure or AWS
  • Microsoft is definitely pushing Docker as a unit of deployment

Docker

  • Not a programming language
  • Not a framework

 

What Docker Is

  • Virtualization technology
    • Server -> VM -> PaaS -> Containers
  • Tool for software
    • Installation, removal, upgrading
    • Distribution
    • Trusting
    • Managing

 

Docker

  • Automates setup/configuration development environments
    • E.g. Far quicker to get up and running with a typical server environment
  • Happy pplace for developers and infrastructure
    • Avoids typical friction between devops and devs
  • Analogy for shipping containers
    • Contains everything you need; container moved from place to place
    • Encapsulation
  • Native for Linux
    • Linux’ containerization strategy became starting point for Docker
  • Installs for OS X and Windows
    • But a bit finicky sometimes
  • It’s Plug In Software (rather than installed software)
    • If it works on your dev machine, it will work anywhere

 

Why Docker?

  • Resource efficiency
    • 26-1 perf improvement over VM
  • Speed
    • Smaller units, quicker build/deploy
    • Leads to talking about microservices
  • Agile
    • Still virtualization, Ship Code containers (ship containers)
  • Lightweight
    • Just Enough OS – only the bits you need in the OS are turned on
  • Consistency
    • Portability and reproducibility. DockerFile, not Click
    • Not relying on how somebody does a particular install or configuration
    • Works on my machine, then it works
  • Microsoft says so
    • Microsoft is moving a lot of stuff towards Docker
    • SPS: How does this strategy fit in with Azure architectures
  • SharePoint story
    • Get things set up at home, but then have trouble rolling out SharePoint on customer’s server
    • Because they don’t necessarily have the same stuff enabled on their server
  • Environmental Drift
    • Avoids having to set up big dev environment to go back and support something from several years ago
    • Docker allows entire environment to be easily reproduced, using Docker File
  • Cattle, not pets
    • Care and feeding that happens when you set up server – pets
    • With cattle, you don’t care that much if one of the servers drops out

 

Things

  • Containers are not virtualization, as we know it
  • Containers can be thought of as shipping containers
    • Everything embedded that you need
  • Containers contain images
  • Images are bundled snapshot
  • Images are deployable
    • Can spin up in Azure, AWS, Google, or in-house
    • Can also move these between platforms
    • Containers don’t tie you to platform
  • Compatibility between Oses
    • Build on OS X, run on Windows
  • What app store did for mobile
    • Docker like multi-platform app store for developers
  • Finicky for OS X and Windows
  • Security by isolation from OS
    • Can’t get from container back to host operating system
    • Helps manage risk
  • Images – immutable file system with execution parameters
  • Containers – instantiations of images (running or inactive)

 

Demo – Simple node.js application

  • Sends a message to console

 

Running it

  • Can run on dev box directly, i.e. running Node

 

Running with Docker

  • Dockerfile – contains instructions for how to run within container
    • Pull down Node
    • Make a directory for app, one for user
    • Do npm install for dependent packages
    • Copy source code down
    • ENTRYPOINT – Says the command to run to start up container
  • .dockerignore – what not to bring down
    • e.g. node_modules
  • Build the container
    • docker build – it runs through docker file and sets everything up
    • At the end, it gives you a number
  • The container exists on the dev machine at this point
  • Now run this image
    • Can map docker’s port to port on host machine
    • docker run
    • Can hit the site at the new port
  • Log on to container
    • docker exec – runs bash shell
  • docker ps
    • List images that are running

 

Demo 2 – Calculating Pi

  • Running locally – spits out a bunch of debug info to console
  • docker run – can run in container
  • Winston logger
    • Log out to directory
    • Can log to external location
  • Typically, you wouldn’t persist data to the Docker container
    • Because the data is lost when you power down the container
    • You’d typically persist data elsewhere

 

Deploy container to production server

  • DockerHub – place for you to deploy your applications to
    • It’s not production yet
  • First, test on your local machine
  • Publish to DockerHub – docker login
    • Tag the image that you created/tested
    • docker push – push to docker hub
  • Push to production, e.g. Azure
    • Docker Container settings in Azure
  • Should work the same on Azure
    • Typically takes 10-15 mins to deploy out to Azure
  • Can do the same for AWS–deploy the same container to AWS
    • “A bit more painful”
    • Use AWS command line tools (you have to install them)
    • Quirky to get push to work
  • Could even envision running the same app on both AWS and Azure
    • More flexibility to react to down time

 

Things

  • Docker pull – pull image from docker hub
  • Docker run – run an image
  • Docker images – list images
  • Docker ps – list all running containers
  • Docker rm – delete docker container
  • Docker rmi – delete docker image

 

Questions

  • More than just Azure and AWS?
    • Yes, e.g. Google, or could build infrastructure in-house
    • But simpler to deploy to Azure or AWS
  • (Sean): Would you typically run SQL Server inside a Docker container?
    • Yes, you can definitely run SQL Server in a Docker container
  • Difference between container and image?
    • Container is sort of the definition of what needs to run, immutable
    • Images are the pieces that start up
    • The image is the running instance
  • If I have various configurations for different environments, how does Docker file manage this?
    • Yes, could use environment variables that get read in the dockerfile
  • Why do you do node:latest, won’t this lead to trouble in the future?
    • In production, you’d want to hard-code a version that you know works for you

That Conference 2017 – SASS and CSS for Developers

That Conference 2017, Kalahari Resort, Lake Delton, WI
SASS and CSS for Developers – Robert Boedigheimer

Day 1, 7 Aug 2017

Disclaimer: This post contains my own thoughts and notes based on attending That Conference 2017 presentations. Some content maps directly to what was originally presented. Other content is paraphrased or represents my own thoughts and opinions and should not be construed as reflecting the opinion of the speakers.

Executive Summary

  • Use CSS for styling your web site
  • SASS makes writing CSS much easier
  • Lots of great constructs for modern UI in both CSS and SASS
  • Some good 3rd party libraries out there (e.g. Bourbon)

About Me

CSS

  • Cascading Style Sheet
  • Describes presentation of a document

Why CSS?

  • Site-wide changes by modifying the styles
  • Support multiple views
  • Leaner pages
  • http://Csszengarden.com
    • Shows how difference style sheets leads to radically different views

Style Rule

  • Selector
    {
    property: value;
    }

Using CSS

  • Inline
    • Style attribute directly on elements
  • Embedded
    • Styles at top of page in <head>
  • External style sheet
    • Style rules collected in .css file
    • Include via <link>
    • (Almost) always do it this way

Cascading

  • Inline first, then top of page, then external

Basic Selectors

  • Element, e.g. h1, div
  • Id
    • #idName
  • Class
    • One or more elements can have this class value
    • .classname

Pseudo Elements and Classes

  • Styles not based on document structure
  • Begins with colon
  • E.g. Style around focused element
    • a:focus { …

Inheritance

  • Elements from document parsed into tree based on structure
    • E.g. Apply style to body, inherited by <div>, <h1> in body

Colors

  • Named colors
    • 17 in CSS 2.1, 140 more in CSS 3
  • RGB

Box Model

  • Margin on outside
  • Border
  • Padding on inside

Common Techniques

  • Cursor
  • display:none – visibility, can turn on/off
  • text-transform – universally apply transform to text, e.g. all caps
  • z-index – overlapping, higher is on top
  • Non-scrolling areas

Reset or Normalize Stylesheet

  • Goal is to reduce browser inconsistencies
  • Reset – set default styles, apply everything yourself
  • Normalize.css – the same across all browsers

RB: Going to Bootstrap for all of our web properties now

CSS 3 Background

  • Series of “Modules”
    • Easier to manage than one big specification
    • Make for easier updates
    • Devices w/constraints can implement just modules that are appropriate to that device
    • Some considered part of “CSS Core”
    • www.w3.org/Style/CSS/

CSS 3 Browser Support

  • http://Caniuse.com
    • Can see which devices/browsers a particular element or feature works on

Browser/Vendor Prefixes

  • Browser vendors can create their own specific settings
  • For stuff not yet standardized
  • Once completed, these specific settings may be removed
  • e.g. grid-ms

Rounded Corners

  • Border-radius
    • e.g. on img
    • Can be different values on different corners
  • Can also use oval corner
  • (More the craze a while back)?

Opacity

  • Specify how opaque an element is
  • Ranges from 0 (fully transparent) to 1 (opaque)
  • F12 in browser, can emulate older versions of IE

CSS 3 Selectors

  • Attribute selectors
    • E{A=V]
    • E[A$=V] attributes ends V
    • Etc
  • input: invalid
    • If input element is invalid, apply this style

Web Fonts

  • Introduced in IE 5, was proposed for CSS 2
  • Watch licensing!
  • Watch FOUT (Flash Of Unstyled Text) and FOIT (Flash of Invisible Text)
  • @font-face

Google Fonts

  • Open Source fonts (600+)
  • <link> to fonts
  • Style-able with CSS
  • Free
  • Developers.google.com/fonts/
  • Fonts.google.com

How

  • <link> to Google site with fonts
  • font-family: ‘Lobster Two’
  • Can host fonts on your own CDN
    • Download the fonts
    • Convert to WOFF or WOFF2
  • Be aware, Google doesn’t display anything while font loading

Animations

  • Property changes in CSS values using keyframes
    • @keyframes AnimName
    • Specify percentages
      • “from” – 0%
      • “to” – 100%

2D Transforms

  • Animations using CSS transforms
  • Matrix translations
  • Transforms are render transforms, independent of layout

Media Queries

  • Media type and 1 or more expressions that check “media features”
  • For responsive design
  • Use
    • Width
    • Height
    • Color
    • Resolution
    • Orientation
  • E.g. Bootstrap
  • Question: Can I get <div> size?
    • No
    • But might be 3rd party package

Other CSS 3 Techniques

  • Box Shadows
  • Gradients
  • Text Shadows
  • Multiple Backgrounds Images
  • Word Wrap

RB: Note that we’re finally getting stuff like gradients and rounded corners at a time when de

Modernizr and Fallbacks

  • Modernizr – detects features in browser
    • Can do alternate method for some feature, e.g. use jQuery for opacity

General CSS Tips

  • Expirations
  • Rt-click, Inspect, Styles tab shows everything applied to an element
    • Can play around with different styles right in the browser

Sass

  • Syntactically Awesome Stylesheets, 2006
  •  CSS preprocessor
  • Sass in designer, compile step, converted to CSS
  • Two syntaxes
    • SCSS (Sassy CSS)  [this is the one you want]

Why Sass?

  • Provides programming concepts for CSS
  • Better organization
  • Reduced maintenance
  • Less vs. Sass
    • Very similar

Tools

  • Ruby – Sass gem
  • VS 2015
    • Web Compiler extension
    • Grunt
    • Gulp
  • Sassmeister.com
    • Experiment

Conventions

  • Myfile-gen.css (output file)

Major Features in Sass

  • Variables
  • _partials, @import
  • Mixins
  • Inheritance
  • Nested Rules and Properties
  • Functions

Variables

  • Avoid “Magic Values” (DRY)
  • $variableName: value;
    • e.g. $primaryColor: Red

_partials

  • Create files to organize SASS and styles in separate files
  • e.g. _variables.scss
  • Then @import “_variables.cscc”;
  • Then everything built into single big .css file
  • So HTML looks the same

Mixins

  • Set of declaratoins that can be reused
  • @mixin to define, @include to reuse
  • Parameters
    • Default values
    • Variable number
  • @content – pass declaration blocks

NB: Should still always look at your CSS to verify what’s getting generates

  • e.g. pay attention to size

Style Inheritance

  • Create classes that inherit from other classes
  • @extend .myBaseClass
  • Compiler will set up style for common stuff and apply to correct elements

Nested Rules and Properties

  • Just syntactic difference, embedding style in another style
  • Nested property
    • border-width generated by border: {width

Control Directives and Expressions

  • @if, @else
    • E.g. check $debugBuild
    • And set $imagePath to correct server
    • NB: for absolute URIs, start with just “//”
  • @for loop
  • @each statement to iterate through a list of items
    • CSS explodes into individual styles

Miscellaneous

  • Debug statements
  • Comments – can disappear or stay in CSS
  • Always modify .scss files, not .css files
  • Check CSS output CSS periodically
  • Minify

Frameworks/Mixin Libraries

  • Bourbon
    • Whole bunch of pre-written scss stuff
    • Only outputs to CSS what you use
  • Compass
  • Bootstrap
    • Switching to Sass/Scss

T-SQL – Where Is a Table Used?

Another “put it in my blog so I don’t lose it” T-SQL nugget.

Nicer than just a raw text-based search, a where-used search for a named table.

select distinct [Found In] = sp.Name, sp.type_desc
  from sys.objects o inner join sys.sql_expression_dependencies  sd on o.object_id = sd.referenced_id
                inner join sys.objects sp on sd.referencing_id = sp.object_id
  where (o.name = 'Cow') 
  order by sp.Name

Handy T-SQL Merge

Inserts records into target that aren’t in source, deletes records that are no longer in source.

MERGE CowTarget AS t
USING CowSource AS s
ON (t.TargetCowId = s.CowId)
WHEN NOT MATCHED BY TARGET THEN
    INSERT (TargetCowId, TargetName, TargetMotto)
	VALUES (CowId, Name, Motto)
WHEN NOT MATCHED BY SOURCE THEN DELETE;

My Git Cheat Sheet

I prefer to use git from the command line, rather than using a GUI-based tool.  Here are my favorite or most-used git commands.

Tools

  • Command line git – posh-git
  • Comes with Git for Windows – https://git-scm.com/download/win
  • After install, you have shortcut to “Git Shell”
  • NOTE: Tab for auto-completion in Git Shell

 

Setting up Kdiff3 as diff/merge tool

  • Download/install Kdiff3
  • Add to PATH: c:\Program Files\Kdiff3 (or equiv)
  • git config –global merge.tool kdiff3
  • git config –global diff.tool kdiff3

 

Cloning – get local of repo

 

List branches (local and remote)

  • git branch -a

 

Create new local branch

  • git branch 170502
  • git checkout -b 170502 master    // create new branch off specified branch (master)

 

Switch to new branch

  • git checkout 170502

 

Switch back to master (or another branch)

  • git checkout master

 

Push new branch (simple git push will suggest this)

  • git push –set-upstream origin 170502

 

Revert local changes (single file or all files)

  • git checkout HEAD <filename>
  • git checkout HEAD .

 

Doing diffs of local changes

  • git difftool <filename>              // diff local file to remote (same branch, if not staged)
  • git difftool master <branchname> — <filename>   // diff file across branches, remote copies
  • git difftool master — <filename>   // diff local file to different branch (remote)

 

Sequence for commit/push changes

  • git add .    — add file to list of things to be committed
  • git commit -m “some message” .    — commit to local repo
  • git push     — push to remote

To unstage a file (reverse of git add)

  • git reset <filename>

To merge changes back to master, from branch

  • On github.com site, find branch, do New Pull Request
    • This just shows all diffs, allows comments, but doesn’t yet create the pull request
  • Add title and comments
  • Review commits and changes
  • Create Pull Request
  • Verify no conflicts
  • (Can leave Pull Request sitting out there at this point)
  • Merge Pull Request
  • Can delete branch after merge (Trash icon in branch list)

 

Update local, after merge

  • git checkout master
    • Back to branch that you merged into
  • git pull
    • Update from remote (you get the just-merged changes)
  • git remote update origin –prune
    • Update local list of remote branches
  • git branch -d 170502
    • Delete local branch that you just merged

 

Switching to new branch that already exists on remote

  • git remote update origin –prune
    • Update local list of remotes
  • git checkout newbranch
    • Automatically set to track remote

 

Abandon a branch

  • git checkout master
    • Get off the branch
  • git branch -d mybranch
    • Delete local
  • Delete branch on github web site

 

Merging

  • Assume you’re working on a feature branch and want to periodically merge from master
  • git checkout master
  • git pull
  • git checkout mybranch
  • git merge master

Merge remote into local changes

  • E.g. if you’re on branch mybranch, have local changes not pushed, and there are other changes already pushed onto mybranch from elsewhere
  • git checkout mybranch
  • git fetch
    • Update remote tracking branches locally, e.g. origin/mybranch
  • git merge origin/mybranch
    • Merge from remote (tracking branch) into your branch
  • Resolve any merge conflicts

If you have conflict

  • git mergetool filewithconflict
  • Resolve in mergetool (e.g. KDiff3) and save
  • Note that merged file is now included in list of files to be committed and that .orig file exists as untracked file
  • Remove untracked orig files
    • Option 1
      • git clean -n
      • git clean -f
    • Option 2 – just delete files

 

See also: Git Cheat Sheat by Tower

 

 

 

WPF Commands – A Pattern that Works

Using commands in WPF can be frustrating. Having so many different ways to do commanding in WPF leads to some confusion. There are multiple ways to wire up commands that are equally correct, though some patterns are cleaner than others.

Below is a pattern that works.

Create static property to expose command

Making the command a property rather than a variable makes the syntax in XAML a bit cleaner.  Using RoutedUICommand allows setting the text for the command. This is useful if you want to use the command in multiple places.

Here’s code for creating the command, e.g. in a MainWindow class:

private static RoutedUICommand _pressMeCommand = new RoutedUICommand("Press Me", "PressMe", typeof(MainWindow));
public static RoutedUICommand PressMeCommand
{
    get { return _pressMeCommand; }
}

Add CanExecute and Executed handlers

Add code in code-behind (or ViewModel) for handlers. Below, we have private handlers in MainWindow. In this example, we have a boolean indicating whether the command can be executed. You could also put the logic directly in CanExecute, if it’s not used elsewhere.

private void PressMe_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = CowboyCanTalk;
}

private void PressMe_Executed(object sender, ExecutedRoutedEventArgs e)
{
    MessageBox.Show("Howdy howdy I'm a cowboy");
}

Set up command binding

You can do this from code or XAML.  Doing it in XAML is perhaps a bit cleaner. Below is an example of binding the above command to its handlers from XAML (for MainWindow). Note that we can just use command name instead of {x:Static syntax because we made the command a property.

<Window.CommandBindings>
    <CommandBinding Command="local:MainWindow.PressMeCommand"
                    CanExecute="PressMe_CanExecute"
                    Executed="PressMe_Executed"/>
</Window.CommandBindings>

 

Wire up a button

Below, we wire a button up to the command.  You could just set Content to text directly. This would be fine to do and is simpler than what we’re doing below. But putting the text into the RoutedUICommand is helpful if you use the command in more than one place (since you specify text in just one place—in the command). And menu items automatically pick up the command text. (NOTE: If you used this pattern for Content regularly, you could just put it in a style to hide the complexity).

<Button Command="local:MainWindow.PressMeCommand"
        Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}" />

Wire up a menu item

Below, we wire up a menu item in a context menu to the same command. Note that here we do have to use the x:Static syntax. But also note that we don’t need to specify text for the menu item—it comes from the RoutedUICommand.

<Window.ContextMenu>
    <ContextMenu>
        <MenuItem Command="{x:Static local:MainWindow.PressMeCommand}" />
    </ContextMenu>
</Window.ContextMenu>

Bottom line

  • We used RoutedUICommand so that we could attach text to the command and avoid specifying text for both button and menu item
  • Binding in XAML is a (tiny) bit less code than doing it in code-behind

Other thoughts

  • You could also use a DelegateCommand pattern, passing in lambdas for both CanExecute and Executed. Use of a DelegateCommand is common in MVVM architectures.