Posts

Showing posts with the label MVVM

Dragging shapes with the mouse in WPF / MVVM

Image
In a recent project I was interested in Dragging shapes with the mouse in a WPF / MVVM Visual Studio project. This post contains an example on how to drag a rectangle from from one canvas location to another using the WPF / MVVM architecture. This project uses Microsoft Visual Studio Community 2019. Step 1: Create a new WPF project: [caption id="attachment_9221" align="alignnone" width="900"] Dragging shapes with the mouse[/caption] Step 2: Add event-handling and event-raising infrastructure Just add the following classes to your project: EventArgs.cs [code language="csharp"] using System; namespace Canvas1 { public class EventArgs<T> : EventArgs { public EventArgs(T value) { Value = value; } public T Value { get; private set; } } } [/code] EventRaiser.cs [code language="csharp"] using System; namespace Canvas1 { public static class EventRaise...

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...

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 = ...

Applying the 2-opt algorithm to travelling salesman problems in C# / WPF

Image
For the Java equivalent see this link: https://www.technical-recipes.com/2017/applying-the-2-opt-algorithm-to-traveling-salesman-problems-in-java/ For the C++ equivalent see this link: https://www.technical-recipes.com/2012/applying-c-implementations-of-2-opt-to-travelling-salesman-problems/ This post demonstrates how to apply the 2-opt algorithm to a number of standard test problems in C# while displaying the results in a WPF style window, while using the MVVM design pattern. See this link for an overview of the two opt algorithm. http://en.wikipedia.org/wiki/2-opt But essentially the 2-opt link swapping heuristic can be summarised by the following steps: The actual 2-opt heuristic can be summarised by the following pseudocode steps, repeating for all feasible combinations of I and k: [code language="text"] 1. take route[1] to route[i-1] and add them in order to new_route 2. take route[i] to route[k] and add them in reverse order to new_route 3. take r...

Using the Supervisor Controller Pattern to access View controls in MVVM

Image
As discussed on a StackOverflow post , this is considered bad practice, so only use this when necessary. Step 1: Create a new WPF project Step 2: Add event handling code A number of classes are needed for doing command bindings in MVVM. Create the following classes and add to your Visual Studio project: RelayCommand.cs [code language="csharp"] using System; using System.Windows.Input; namespace SupervisorControllingPattern { 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(nameof(execute)); _execute = execute; _canExecute = canExecute; ...

How to use Interaction Triggers to handle user-initiated events in WPF / MVVM

Image
Example scenario: User clicks the mouse in a WPF application - how do we 'listen' to that event in order to trigger and handle an event in the main code? A possible solution is to use in WPF MVVM. See this post to learn how to do this using MvvmLight: https://www.technical-recipes.com/2017/handling-mouse-events-in-wpf-mvvm-using-mvvmlight-event-triggers/ Here is an example WPF implementation created in Visual Studio 2015. Step 1: Create a WPF application Step 2: Add the System.Windows.Interactivity reference UPDATE For more recent versions of .NET see this StackOverflow post on how to upgrade from older versions of Interactivity to the latest NuGet package: https://stackoverflow.com/questions/8360209/how-to-add-system-windows-interactivity-to-project/56240223#56240223 If you need to migrate from an older version, then do these steps: 1. Remove reference to “Microsoft.Expression.Interactions” and “System.Windows.Interactivity” 2. Install the Microsof...

Using the Mediator pattern in MVVM / WPF

Image
Some instructions on how to use the Mediator design pattern as a means of allowing communication between ViewModel classes in your MVVM / WPF application. In this example I use the Mediator as a means of communicating to the main window which view to display when the user clicks a button on either of the child views, View1 and View2. Step 1: Create a new WPF application Step 2: Add event handling classes EventArgs.cs [code language="csharp"] using System; namespace MvvmSwitchViews { public class EventArgs<T> : EventArgs { public EventArgs(T value) { Value = value; } public T Value { get; private set; } } } [/code] EventRaiser.cs [code language="csharp"] using System; namespace MvvmSwitchViews { public static class EventRaiser { public static void Raise(this EventHandler handler, object sender) { if (handler != null) { ...

Binding data to ListView controls in WPF using MVVM

Image
Some few tips and instructions on how to bind data items contained in a List to a WPF ListView. Create a new empty WPF Application: Then create a new ViewModel class for out MainWindow.xaml which will be used to create and access the data items that are bound to the ListView: Our MainWindowViewModel class has a getter for obtaining the list of data items we wish to present in the ListView control: MainWindowViewModel.cs [code language="csharp"] using System.Collections.Generic; namespace ListViewWpf { public class Item { public Item(string name, string matches) { Name = name; Matches = matches; } public string Name { get; set; } public string Matches { get; set; } } public class ItemHandler { public ItemHandler() { Items = new List<Item>(); } public List<Item> Items { get; private set; } public void Add(Item item) { Items.Ad...

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 ...

Switching between WPF XAML views using MVVM DataTriggers

Image
Related post: https://www.technical-recipes.com/2016/switching-between-wpf-xaml-views-using-mvvm-datatemplate/ This post addresses the problem of being able to switch between different views based on the property of a ViewModel class. To get started in Visual Studio, create a new WPF Application: So that when we build and run the application we have a blank window like this: To demonstrate how WPF windows can be made to switch between different views, create two new XAML views, View1.xaml and View2.xaml, each consisting of a simple TextBlock containing different texts to demonstrate that the views are different. In your Visual Studio project, right-click your project folder and select Add > New Item. Select User Control (WPF) and name your file as View1.xaml: In the xaml portion of the file, insert the code to display the Text in the view as follows: [code language="xml"] <UserControl x:Class="XamlSwitching.View1" xmlns=...