Posts

Showing posts from July, 2016

Binding a XAML control visibility to a ViewModel variable in WPF

Image
Some instructions on how to bind the visibility of a XAML button control to a boolean value in a ViewModel class. 1. Create a new WPF application 2. Add the View Model class Right click your project folder and select Add > New Item > Class. Name your class MainWindowViewModel.cs: In your ViewModel class include the property to get the visibility setting. For reasons of simplicity this simply returns a value of true for now, but in your own implementations, feel free to make the getters and setters do what you like. [code language="csharp"] using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Visibility { public class MainWindowViewModel { public bool ButtonVisibility { get { return true; } } } } [/code] 3. Update your MainWindow.xaml code to do the following: - add a button - set the DataContext property - declare and use ...

Using RelayCommand / ICommand to handle events in WPF and MVVM

Image
A step-by-step guide to using the RelayCommand class (based on ICommand) as means of handling user-initiated events in WPF / MVVM / XAML. 1. Create a new WPF application 2. Add the View Model class Right click your project folder and select Add > New Item > Class. Name your class MainWindowViewModel.cs: The MainWindowViewModel class will be used implement a very simple function to display a message box when it receives the incoming event. Add the functions and code to MainWindowViewModel.cs as follows: [code language="csharp"] using System.Windows; using System.Windows.Input; namespace Command { public class MainWindowViewModel { private ICommand _command; public ICommand Command { get { return _command ?? (_command = new RelayCommand( x => { DoStuff(); })); } } private static void DoStuff() { ...