Posts

Showing posts from September, 2017

Adding tab items dynamically in WPF / MVVM

Image
Some instructions on how to add/remove tab items within a WPF / MVVM setting. Step 1: Create a new WPF application Step 2: Add classes to implement ICommand RelayCommand.cs [code language="csharp"] using System; using System.Windows.Input; namespace Tabs { public class RelayCommand<T> : ICommand { private readonly Predicate<T> _canExecute; private readonly Action<T> _execute; public RelayCommand(Action<T> execute) : this(execute, null) { _execute = execute; } public RelayCommand(Action<T> execute, Predicate<T> canExecute) { if (execute == null) { throw new ArgumentNullException("execute"); } _execute = execute; _canExecute = canExecute; } public bool CanExecute(object parameter) { return _canExecute == null || _canExecute((T)parameter); } public vo...

How to stop C# async methods

Image
Scenario: a WPF application which when the user presses a button goes off and runs something asynchronously , so that the user is still able to interact with the user interface without it freezing. Not only that, I want to be able to stop the asynchronous operation on receipt of another button press so that it exits graciously. The is where CancellationToken structure comes in, that is used to propagates notifications that operations should be cancelled. Some useful StackOverflow resources on this subject can be found here: https://stackoverflow.com/questions/15614991/simply-stop-an-async-method https://stackoverflow.com/questions/7343211/cancelling-a-task-is-throwing-an-exception Some instructions to implement this in a WPF / MVVM kind of environment are given: Step 1: Create a WPF application Step 2: Include event-handling classes Specifically this means classes to implement ICommand RelayCommand.cs [code language="csharp"] using System; using Sy...

Binding the visibility of DataGridColumn in WPF / MVVM

Image
See this StackOverflow answer for the original inspiration. Notable quote: "First of all DataGridTextColumn or any other supported dataGrid columns doesn't lie in Visual tree of DataGrid. Hence, by default it doesn't inherit DataContext of DataGrid. But, it works for Binding DP only and for not other DP's on DataGridColumn." Here is an example of how to achieve this in a Visual Studio WPF application. Step 1: Create a Visual Studio WPF application: Step 2: Create a Freezable class "Freezable objects can inherit the DataContext even when they’re not in the visual or logical tree. So, we can take advantage of that to our use. First create class inheriting from Freezable and Data DP which we can use to bind in XAML". BindingProxy.cs [code language="csharp"] using System.Windows; namespace DataGridColumnVisibility { public class BindingProxy : Freezable { public static readonly DependencyProperty DataProperty = ...