One-bytes #2: Selection in WPF, OnPropertyChanged parameters

*** #2.1 Item selection in WPF selector-enabled items control***
In WPF we can use multiple types of controls to display collections of items which allow user to select one or multiple items from the collection. In this post I’m going to discuss what single selection possibilities they offer.
Let’s start with inheritance hierarchy – controls that allow such selection inherit from System.Windows.Controls.Primitives.Selector. If we take a look at what properties they have we find four that may be involved in selection process:

  •  SelectedIndex – Gets or sets the index of the first item in the current selection or returns negative one (-1) if the selection is empty.
  • SelectedItem – Gets or sets the first item in the current selection or returns null if the selection is empty
  • SelectedValue – Gets or sets the value of the SelectedItem, obtained by using SelectedValuePath.
  • SelectedValuePath – Gets or sets the path that is used to get the SelectedValue from the SelectedItem.
    source: msdn.microsoft.com

So, there are three ways get the selected item: i) its integer index in the collection, ii) the item itself, iii) one desired value from the item. 
I have prepared a quick demo to show that. The app displays a ListBox of custom class objects and once an item is selected displays all three ways to present the selection. Let’s take a look into the code, starting with the class of objects that our list will contain:

The list will be generated and stored in view model. The view model will also have three public properties: i) ItemSelectedIndex of type integer bound to SelectedIndex property of  our ListBox, ii) ItemSelectedItem of type Item bound to SelectedItem, iii) ItemSelectedValue of type string bound to SelectedValue. Let’s take a look at complete ViewModel class:

And now the most important part – the view. As mentioned above as a container for collection we will use ListBox and bound properties as it was described when discussing the view model class. The only thing that’s left is setting correct value to SelectedValuePath property. In this case we want to use Name property of our item class so we need to set SelectedValuePath to “Name”. Here’s how to set the ListBox up:

Now, to use the selected index, item or value which are bound to corresponding properties in view model we need to add some controls and again bound them to view model properties:

And that’s it. To sum things up – there are three ways to access selected item in a selector control in WPF: by its index, by the item itself or by one particular value in the item.

*** #2.2 Passing property name to OnPropertyChanged()***
Second thing I want to mention today is a hint how to make invoking OnPropertyChanged() method in a property setter a bit more controlled when not using any MVVM framework.
ViewModels usually implement INotifyPropertyChanged interface which purpose is to notify views when a property has been updated. This is done by invoking OnPropertyChanged method with property name passed as a parameter.

That is not the best way. What if we decide to change the property name and the backing field can also be changed somewhere else? In this case we need to go and manually change the hard-coded property name. So what can be done instead is this:

Having passed the parameter this way we can simply go to the property, right click and rename it using Visual Studio renaming tool which will update all calls to this property. Definitely better!

One-bytes #1: Menu item commands, boxing vs. ToString()

Hello there!
With this post I’m starting new category: one-bytes. These posts will be compiled of two or three shorter forms abut things that don’t qualify for so to say full-size post. Name of the category refers to snack meals, so called one-bite foods: one bite => one byte. Quick to prepare, good to get your taste-buds tingling.  Enjoy!

*** #1.1 Binding a command to MenuItem in ContextMenu ***
It happend one time that I had been struggling with binding a command to a MenuItem in ContextMenu. The code was more or less like this:

It turned out that since ContextMenu is not present in WPF visual tree it was not possible to bind the command as it’s usually done. The solution was to use BindingProxy class that inherits from Freezable.

Having this class we can create its instance as a resource (in my case it was an user control) and set the Data property to {Binding}:

This will bound the Data property to whatever is set as DataContext in the user control itself. Now, through the BindingProxy instance we can access that DataContext outside the visual tree:

This solution was proposed by Thomas Levesque.
Sources:
Blog post by Thomas Levesque
Question on StackOverflow

*** #1.2 String.Format() vs. boxing ***
There is a thing using String.Format() method with value types (such as integers). That thing is the fact that this method takes objects as args and if a value type given as parameter it will be boxed. Boxing is a process when a value type is converted to an object. That involves moving the value from stack to heap and replacing it on a stack with a reference to heap address where the actual value is stored. (More on boxing/unboxing can be found here: [link]).
So, what can be done to avoid that – simply pass arguments with ToString() method invoked. This will save a bit on performance – that’s the theory. So I tested it. I take an array of one million integers and another array with the same amount of doubles and pass them into String.Format() method. And the theory is confirmed – avoiding boxing by invoking ToString() method makes it faster.

To make the results reliable I arranged everything as unit tests run one after another (not parallel) and the actual tests were preceded by a test that did nothing – that is to make sure that the filling arrays in test class constructor does not distort actual test running time. So the results are that the process without boxing is faster by 3,7% for doubles and 4,9% for integers. Please, keep in mind that the test sample was one million values.
Does it mean that it’s no point in invoking ToString()? My opinion is that in this case boxing operation is redundant and not necessary so it should be avoided.

Inventor API: Custom add-in #2 – Functionality and UI

Hello!
Writing our add-in for Inventor continues! Agenda for today’s post is simple: first I will write a word or two about what is the functionality of the add-in, then I will present the UI and what settings it provides, finally I will present the code.

FUNCTIONALITY

So, what will the add-in do? It allows user to place initial break to the biggest view in the drawing. It is rarely required in real world but the purpose of this demonstration is not to write something widely useful but to present how to write basic add-in for Inventor. Nevertheless, I wouldn’t be surprised if someone finds actual use for it. Feel free to do that 🙂
Inventor allows to set some parameters of the break. First and the most important is orientation. In our case that will be determined not by the user but automatically depending on proportions of the view. The rest will be allowed for customisation. As this is not an Inventor tutorial I am not going to describe in details how to manually add the break and what exactly can be customised. For such pieces of information you can easily find something on YouTube (for example this[1]).

UI PRESENTATION

As our add-in is very simple its UI is equally simple. Combo box for break style, slider for number of symbols (for structural style), text box gap which value will be converted to double and is expressed in centimetres, and slider ratio of how much of the view will be removed (minimum is 10%, maximum is 90%, however if the view is to small the break will not be applied). This small dialog is built in WPF and follows the MVVM pattern.

CODE

As this add-in will use WPF user interface I want it to follow the MVVM pattern, therefore we need model and view-model.

Model
So, let’s start with the model as this one is the simplest:

Style parameter is represented by an integer property backed by a field. The property setter allows only two values: 0 and 1 – that’s how two possible options are represented. Other possibility could be for instance a boolean, however integer is simpler to use with combo box. Similar situation with Symbols where setter allows only 1, 2, or 3 to be assigned; and with Range which can vary from 10 to 90. Gap is auto-property of type double. Class constructor sets initial values which are hard-coded. Natural extension would be to save those values somewhere so they are saved between sessions, however it’n not the point at the minute. The model class SettingsModel is additionally abstracted by ISettingsModel interface.

View-model
The view-model is slightly more complicated, but still quite simple.

First and foremost – it implements INotifyPropertyChanged interface. Fields and properties reflect the model, there are two things that require explanation. Range field/property backing field is of type double which is consistent with its counterpart in the model, while property is of type int which is consistent with slider’s value property. Gap field/property is of type string which will be bound to a textbox. The view-model also contains reference to model which is set via default constructor, constructor also assigns values from the model to respective fields in view-model. There is only one method which is used to save values from view-model to model; and there is only one command which invokes SaveToModel() method and closes settings dialog.

As mentioned SaveCommand is used to save values from view-model to model. It can be executed only when Gap value in view-model can be parsed to doubleExecute(object parameter) method casts parameter to type Window and invokes its Close() method to close the window. This require passing open instance of settings window to command parameter, which will be explained below.

View
Now, the view. There is one trick with WPF windows in Inventor add-in. If you try to add a WPF component to the project you will see that only user control is available, but the problem is that we need a window. A way to tackle that (source[2]) is to add what we can – a user control, and then change it to window. You need to do that in XAML code of the window and in the C# code behind. In XAML change root node to <Window>…</Window>, in C# code modify your class so it inherits from Window not from UserControl. And that’s it.

The only intresting thing in the XAML code above is how current instance of window is passed as command parameter:

The command parameter value is set to binding with RelativeSource set again to RelativeSource in FindAncestor mode with type of Window. This way  the current instance of window will be passed as command parameter which in turn is closed by the command.
Other than that, there are not exceptional things in the XAML, simply built UI with typical binding to view-model.
What you probably noticed, is that data-context is not set, and instance of view-model is not created in XAML, which requires the view-model to have parameter-less constructor, therefore some changes to add-inn StandardAddInServer main class are required.
Another thing worth mentioning is that closing (without saving settings to model) by clicking ‘Cancel’ button is achieved simply by an event assigned to that button, not by a command. This way to do that is much, much simpler than a command and because of the fact that it doesn’t interact with neither model nor view-model it doesn’t break the MVVM pattern.

Updates in StandardAddInServer
First thing that we need to do is to instantiate a model. The main class will be equipped in private field of type ISettingsModel […]

[…] which will be initialised in the class’ constructor.

The last thing we need to do is open the settings window when appropriate button is clicked. To do that we need a method that will be fired when the button is clicked.

The method above creates new settings window, sets it data-context to new instance of SettingsViewModel with current model as constructor’s parameter and finally shows the window as dialog.

And that’s it. Next (and the last) step will be to make ‘Apply!’ button to work. So, don’t forget to check my blog a little bit later.
Thanks, Michal!

GitHub repo: https://github.com/mickaj/AutoBreaker-Inventor

Sources:
[1] – https://www.youtube.com/watch?v=BzUAb9Qvu98
[2] – http://adndevblog.typepad.com/manufacturing/2015/11/wpf-window-inside-an-inventor-add-in.html

Inventor API – Custom add-in Part #1
Inventor API – Custom add-in Part #3

WPF: TreeView control

Hello there! It’s been a while since I finished GetNoticed contest and my last post here. I am done with SheetMetalArranger – at least for the minute. But that the contest is done doesn’t mean that I am done with programming. Not at all!

I started new project (maybe one time I will get back to SheetMetalArranger to improve it, but after ten weeks I need something fresh now). It doesn’t matter what the project is about at the minute (I will probably write a post or two about that), the important thing is that I’m continuing with WPF and the time has come to take a closer look at TreeView control.

Basics

TreeView control is used to display hierarchically organised structure. The best example is folder tree, for instance the one you have in Windows Explorer.

Here’s simplest example:

To build hard-coded tree you simply nest one <TreeViewItem> into another and build your structure. Notice that Header property is what is going to be displayed in your application. There are two other properties of TreeViewItem that should be mentioned here: IsExpanded and IsSelected which are pretty much self-explanatory but it is worth to mention them as they are fundamental for controlling behaviour of the control.

Binding

Binding a collection to TreeView can be easily achieved, it is no different as other controls. You simply bind a collection to ItemsSource property. But the tricky thing is that you need to reflect the hierarchy somehow. One way to do that could be binding a collection that contains objects of class TreeViewItem which is equipped in collection Items which contains child objects. Here’s the same example but with the difference that all data is stored in data model:

1) Lets start with the data model: our library node will consist of name, collection of books (stored as strings) and collection of sub-nodes.

2) Our actual data for the purpose of this example will be stored in static class with one static method GetData() that return instance of LibContainer

3) Our view model will consist of observalbe collection of TreeViewItems and in its constructor it will get data from the above static class. Inside the view model there is also one small private method that converts LibContainers to TreeViewItems

4) We set instance of view model and set it as data context. For example as below. Now, after that our tree view can be simplified just to only one line.

Load on-demand

The above example is nice and easy. It gets a bit more complicated when you want to load content of your tree view on-demand when content of your tree is huge and loading all data at once would be lengthy operation – I guess that’s common situation.

To achieve that we need to build custom class that will replace TreeViewItems in collection in our view model. That class must have: 1) collection of child items of the same class, 2) Parent, IsExpanded and IsSelected properties, 3) method to load children, 4) property that defines if the element can be expanded.

Here’s our example build this way:

What’s important in the code above is that Children collection must contain dummy element before actual elements are loaded. This is necessary because it would not be possible to expand the element, therefore it would not be possible to execute method that load further elements.

ViewModel class will now have only collection of TreeElement and will gather data from DataModel in its constructor.

Now, we need to define our TreeView control to display our custom items correctly. This is done by creating local style where we bind IsExpanded and IsSelected properties of TreeViewItem with counterparting properties of our custom TreeElement

And that’s it. This is how I use TreeView control. Possible extension to the above would be to create custom WPF control to handle custom types of tree elements and equip it with dependency property that exposes currently selected item. But that’s easy to do and isn’t in any way specific to TreeView.

So, thanks for today and good luck!

Sources:
WPF 4.5 Księga eksperta. Podręcznikprogramisty WPF 4.5! Adam Nathan (translated by Paweł Gonera, Ireneusz Jakóbik), published by HELION S.A 2005
https://www.codeproject.com/Articles/26288/Simplifying-the-WPF-TreeView-by-Using-the-ViewMode

 

GetNoticed IT#9: User control with data grid and observable collection

Good morning!
It’s been 10 days since my last post so the time is high! Today I’m going to write how to bind an observable collection of custom objects to a data grid in a WPF user control. Some time ago I wrote a post about basic use of user controls (see here) so this post you are reading right now can be considered as extension of the first one.

Objects in collection
Let’s start with preparing a class which objects will be stored in our collection. I won’t look for anything bright, I will just use something for my project: the class will store information about rectangles: height, width, margin and if a rectangle can be rotated. Additionally the class will have a property that returns area of a rectangle.

That’s the basic implementation of our ListedItem class. Now, to use it with observable collection in a way that it is bound to datagrid in UI and all values are automatically refreshed it is necessary to implement INotifyPropertyChanged. At the same time it would be wise to tweak our class a little bit: properties Height and Width cannot be smaller than 1. Also, when implementing INotifyPropertyChanged it is necessary to notify about Area property changed when any of Height or Width changes.

The last step would be to add a parameterless constructor that assigns all properties with default values.

View model
Our observable collection will be stored in our view model.

In the constructor of MainViewModel class we initialize the collection and add first item. And that’s for the purpose of this post is sufficient.

User control
Out user control will consist only of data grid inside a group box therefore the XAML is very simple.

What’s important in the code above are two things marked above: 1) assigning name to the user control (“this”), 2) defining data grid and its binding to dependency property Source.
Now, let’s move on to the code-behind the user control where we define dependency property.

We need to set the property of type ObservableCollection<ListedItem>, owner type ItemsList (as the name of our user control class) and name Source.

View
Now the last thing: combining all together in view. First of all we need to add namespace that contains our user control to namespaces used by the UI, create an instance of view model that is going to be used be the UI and set it as data context of top level grid.

To add our user control to the UI and bind observable collection for view model:

In this case binding mode is set as TwoWay because I want changes made by user in data grid to be reflected in collection in view model. But you have complete freedom here, that depends only on your needs.

So, basically that’s it. Before I finish few notes about customising the data grid.

Columns
The implementation above will generate columns in data grid according to properties exposed by elements in collection. But that is not the only way. you can set up your own names, for instance when you’re building multi-language app. To do that you need first set AutoGenerateColumns property of your data grid to false, and second define the columns manually. In our case that would be:

Note, that you need to be careful to use correct column type and to set binding correctly. In our case Area property is generated automatically therefore user must not be able to put anything in that column. To achieve that I had to set binding mode for this column to OneWay.

User edits
Depending on particular needs you may want to disable editing your data grid. There are certain properties that allows you to customise access to your data grid. To disable any edits you must set IsReadOnly to true, to make more precise customisation you can use set of CanUser properties which are pretty self-explanatory so there’s no point in describing them here.

Thanks for today, I hope that it’s gonna be somehow useful for you.
Regards, Michal

Sources:
https://msdn.microsoft.com/en-us/library/ee340710(v=vs.110).aspx
http://helion.pl/ksiazki/mvvm-i-xaml-w-visual-studio-2015-jacek-matulewski,xamlmv.htm

 

GetNoticed IT#02: User controls in WPF

Hello!
I’m continuing learning WPF. Recently, I’ve put my focus on user controls. As I did not spend too much time mastering WinForms I didn’t do anything in this matter so far.
Default controls library offers basic set of controls you can use to build a WPF user interface. It’s easy to find a case where the same set of controls will be used frequently in your UI. First thing that comes to my mind: a tabbed interface which display some data. To make it efficient it would be reasonable to create a pattern of how those basic controls will be used in our data tab, so once user open new tab it will contain this pattern. And a user control can be understood as such.
In this presentation I will prepare an application that display a person’s details. It will consist of list of users, buttons to show details of existing person and to add new person and a tabbed panel where the application will show details of selected (or new person).

Model
The model will consist of two class: both public; one is Person class which describes one particular person some basic details, the second one ListData contains a list of all persons and some properties used to bind them with the UI. ListData can be more or less considered in this case as a view model.

PersonControl
To start building your customised control you simply need to add new item to the project and select WPF user control – that’s easy to find, no need to explain.
And here’s XAML and code-behind for the control:

The control consists of text blocks which display properties of person bound to the control. In the code-behind you can see a dependency property declared. It is of type Person (more on dependency properties here). That allows us to bind an object of this class directly to the control. What also needs to be mentioned is that the control is given name x:Name=”this”. That in turn is required to internally (in boundaries of the control itself) bind a dependency property to a certain text block in XAML <TextBlock Text=”{Binding ElementName=this, Path=ThisPerson.Balance}”/> .

As mentioned earlier class ListData would be our view model.  It implements INotifyPropertyChanged interface and shares two properties: PersonIndex and SelectedPerson. The first one is bound to SelectedIndex property of a combo box with list of all available persons and the second one is bound to our custom control.

What’s interesting is that setter for PersonIndex also changes SelectedPerson property. That works in that way that switching an item in combo box (which is bound two-way with PersonIndex) will also inflict a change in SelectedPerson.
That’s pretty simple way to build controls specifically for displaying data from custom objects. I would much appreciate if anyone smarter than me is reading that and thinks that it is not a good practice (as it is actually coupled with the model but I think it could be easily improved by introducing some abstractions).
Source code available on GitHub here: https://github.com/mickaj/PersonsUCDemo

So, that’s it for today. My plans for the weekend is to improve a bit the Guillotine algorithm I wrote implementation last week.
And here’s a goodbye riddle: in the demo you can find three persons defined. The last one is Pierre Aronnax. Who is he?

Cheers, Michal

WPF: Static resources and styling

Nau mai!
Today it’s going to be about styling in WPF. So far all UIs I designed in WPF had all controls styled in their definitions. This worked sufficiently well as I have not yet built any complex application. But, it is obvious that is not to any degree an effective way to achieve styling of UI elements. My understanding of how to built bigger and more complex UI and to keep them consistent appearance-wise would be to use something like CSS in web design. And in fact WPF allows us to use similar method. Create a definition of element’s look and then assign it to an actual control in the interface.
Styles can be defined for each container. For instance, you can define style for elements in a panel, but you can also define style for whole window or even application.

Internal styles
Let’s start with styles defined inside a file where the styles are going to be used. The code below presents how to define styles available for all window elements.

In the example above we create static resources that are available for all elements in current window. Then, inside resource we create a style definition where we set style key and target type (this is optional, however to have access to control-specific properties it is recommended to do so). Now, to set specific property we use property setters where we declare a property name and assign value to it. Once, the style is defined it can be assigned to a control. The XAML code above would generate that window:

To define styles available for elements only in one container (e.g. in a panel) we need almost exactly the same code. The only change would be that the resources are set for a stack panel not for window (StackPanel.Resources instead of Window.Resources).

External resources
To reuse the same styling in multiple windows we need to create a resource dictionary. It is nothing else than a XAML file. Simply right click on your project in Solution Explorer and go Add and then Resource Dictionary.

In that file you declare styles as you like for various controls, then you put path to this file in Resources section of any container you want to style:

It is also possible to put it in application’s resources having the styles available in whole app.

In the code above there are MergedDictionaries specified. This allows to use multiple resource dictionaries in one container. If a key exists in more than one source dictionaries the last one specified will be used.

Triggers
Triggers can be used to specify certain conditions that must occur to enable the style (the most common example: a button is hovered).

The code above will make a button to change its properties if IsMouseOver property is set to true.
So, that’s it for today. I know that styling in WPF is much more vast topic and surely I will come back to it, but this basic introduction is sufficient for me for the time being.
Thanks you, Michal.

EratoWPF – Sieve of Eratosthenes (WPF and MVVM)

Hello!
I have just finished another simple app. This time it’s an application to look for prime numbers. The app is again simple but the reason for that is I wanted to make an approach to something new. This time it is MVVM design pattern.
What is MVVM? It is a software design pattern which goal is to separate user interface form application’s logic and data model.
M – model – data source
V – view – user interface
VM – view model – logic and a ‘go-between’ model and view
Use of MVVM pattern allows for a project to be simultaneously developed by a graphic designer and a coder as the UI does not (and should not) require any code-behind. Another advantage is that the whole logic and data-model can be quickly ported to new UI. Microsoft emphasises use of Blend for Visual Studio which is a graphic-design tool for creating (not only, but also) WPF user interfaces to design UIs. In this case I didn’t follow that advice. XAML editor in Visual Studio is sufficient for me.

So, how the separation is achieved? In EratoWPF case, first  I created a model which is PrimeNumbers class in PrimeNumbers.cs file. To be sure that it is working as it should I also created another project called PrimeNumbersSieveTester which is a small console application that tests the class.
Next, I started building the view in XAML with input text boxes and some buttons to run the algorithm or clear inputs.
Finally, I started building the view model. It represents the content of the UI. The view model also privately instantiates the model. The UI will not have access to it.

Binding
To allow the UI use (to display and/or update) properties from view model we use data binding. To achieve that first we need to set data-context for the UI.

The XAML code above will create an object viewModel which is an instance of ViewModel class. The code below will set main grid data-context to viewModel.

Now, to bind a property from viewModel to a control in WPF user interfaces:

The code above binds Text property of a text box to InputRangeStart property in viewModel and IsEnabled to InputsEnabled. Modes specify type of binding. OneWay allows only to dispaly data from viewModelTwoWay allows also to update data in viewModel.
This also requires a view model to implement INotifyPropertChanged. It’s quite simple:

That creates an event handler which is fired every time a property is changed. To set up a property to fire that event it is required to invoke OnPropertyChanged(“PropertyName”); method in a set accessor of this property.

Commands
As it was written earlier in this post, an application designed according to MVVM pattern should not have any code-behind. Therefore, it is required to use commands instead of events.
First, we need to create command class which implements ICommand interface:

That is basic implementation of a command. However, if a command operates on view model instance it is advisable to add private and readonly field for view model and create a constructor that sets it to viewModel defined in XAML.

After that, we need to create an instance of this command in our view model to allow it to be bound to a control in the UI.

Now, to bind the command to a control:

And that’s pretty much it. This is very basic introduction to MVVM, but good enough for a start. There are other aspects of MVVM (such as converters or dependency properties any many many more that I am not aware of at the moment) but I am sure that I’ll come to that as well. As they say: Rome wasn’t build in a day!
Good luck!

Source code: https://github.com/mickaj/EratoWPF
Readme: https://mkajzer.pl/?page_id=200
Installer: https://mkajzer.pl/download/EratoWPF/EratoWPF_installer.zip

Recommended reading (in Polish): “MVVM i XAML w Visual Studio 2015”, Jacek Matulewski, published by Helion, 2016, ISBN: 978-83-283-2867-9
http://helion.pl/ksiazki/mvvm-i-xaml-w-visual-studio-2015-jacek-matulewski,xamlmv.htm

RomanDecimalConverter

Greetings,
I have finished another quick project. The plan for this was to introduce myself to WPF and XAML. My general thoughts are that despite that WinForms seems to be easier and quicker way to design a Windows application I find WPF more organised and more controllable that WinForms. I designed all windows for this application using only XAML editor (not the visual one) in Visual Studio. That gives better understanding what is happening with the window.

The application itself is quite simple: it converts Roman numbers to Decimal, and the other way around. Algorithms of conversion are quite simple so I won’t describe them here (they can be found in readme file, or by analysing the code).

That was quite a nice way to leap into WPF. Next week, I’m going to three-day basics of .NET programming course which I hope will give me more insight to WPF and MVVM model (which, I’ve deducted from some of the YouTube lectures about WPF, is essential for writing a well-organised and maintainable applications).

Stay tuned!

ClickOnce installer (*.zip)
Source code (*.zip)
Readme file (*.txt)