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: http://mkajzer.pl/?page_id=200
Installer: http://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

Interfaces

Hello!
Today I’m going to write a word or two about interfaces. So, what are they? In simple words an interface is a statement that a class has certain features defined by the interface. It says that a class is equipped in certain capabilities. Here’s an abstract example. Do you recall pre-smartphones era, circa 2000? Cell phones that time had two primary functions: voice call and text messaging. But some of the fancier models had colour screen, photo camera etc. To reflect that we would say that this fancy phone is of Phone class and implement IPhotoCamera interface.
Let’s create simple Phone class with methods to make a call and send text message:

And a simplest interface I can possibly imagine:

There are few things you need to know about interfaces:
1) Interfaces can consist only of methods, properties, events or indexers
2) Implementation of methods takes place in actual class which inherits the interface. Signature of implementation must be complement with its definition in interface.
3) Interfaces can be generic.
4) Definition of a property interface includes only get; and/or set; accessor keyword without actual implementation.
5) Naming convention is to add capital ‘I’ prefix before the name of an interface.
Let’s get back to our example. Our IPhotoCamera interface contains definition of one property and one method. If a class inherits this interface it must implement what’s defined in the interface.

Now, let’s move back to our main. We can test our two classes by simply invoking methods that are available. But, there’s no use for interfaces so far. This could be easily achieved without it. Class HiEndPhone inherits after CellPhone class and could have its unique method specified without use of interfaces. But using interfaces allows us to write method specifically for objects that implement an interface that will access only what was specified in interface declaration.

But all this above is not the most important thing about interfaces. In C# a class can inherit from only one class. However, this limitation does not include interfaces. You can implement in your class as many interfaces as you want. That’s the most important feature in the concept of interfaces.
To sum things up: an interface is an indication of certain capabilities that a class must implement and actually implement; a class can implement multiple interfaces; naming convention for interfaces is to precede its actual name with capital ‘I’ letter.
Regards, Michal

MSDN: https://msdn.microsoft.com/en-us/library/ms173156.aspx?f=255&MSPPError=-2147217396

Delegates, Lambda expressions, callbacks and events

Shalom!
Since my completion of the course (read here) I have turned my focus onto delegates and events. All in order to fully comprehend the MVVM pattern. This post will be mainly about delegates and events, but I will also write a bit some of the related topics (Lambda expressions, callbacks and Func, Action and Predicate delegates).

Delegates
In short words delegates are types that can hold a reference to methods. Those methods must be consistent with delegate type signature. They can hold a named methods, anonymous methods and Lambda expressions. Interesting feature of a delegate is that its instance can hold references to more than one method which can be added/removed simply by using + or – operator. Here’s an example of delegate signature:

To create an instance of a delegate:

To invoke methods referenced in the delegate simply invoke it exactly the same way as regular methods or use Invoke(); method.

Delegate can hold references to more than one method. These methods will be invoked in the same order as they were added. If a delegate returns a value it will return value from the very last method in its invocation list.


Anonymous methods and Lambda expressions
Anonymous method is a method which is declared and its body is defined when assigning it to a delegate. Lambda expressions (introduced in C# version 3.0) are more or less the same as anonymous methods but with simplified syntax.

Lambda expressions use ‘=>‘ operator. It can be understood as ‘becomes’ or ‘goes to’. In other words what’s before the operator is inputs and what’s after the operator it output. Input and output has to be consistent with delegate type to which you want to assign the expression. If there is only one instruction after the operator and the delegate returns a value it is not necessary to use ‘return‘ keyword.

Func, Action, Predicate
These are ‘built-in’ generic delegate types introduced in C# 3.0. Generic parameters represents type of arguments and type of returned value (if any).

One of the purpose where you can use predicates is filtering a collection. For example, you can use RemoveAll(Predicate<T> match); method to remove from a list all elements that satisfy the condition.

Callbacks
While doing research about delegates it was often claimed that main purpose of delegates is allowing communication between two classes. Original meaning of ‘delegate’ noun is someone who is sent to other party with a message. And this is how delegates should also be comprehended in C# and programming.
Imagine that there is a class with a method that takes a significant amount of time to execute. To keep application responsive it would be worth to have some feedback about the status or progress of this time-costly method. It is possible to achieve via callbacks.
Here’s a Calculation class with a method simulating some lengthy calculations:

This class defines CallBack delegate type which takes one integer argument and doesn’t return any value. This delegate is also an argument in our Process method that want’s to send feedback to another class which is achieved by invoking that argument somewhere in the method.
UI for this example is a WPF window. It consists of a textbox where user gives number of cycles that Process method will run and a button that executes that method. There is also a numeric indicator of current cycle and a progress bar. Those two controls receive feedback from Process method. There is also a text box to witness that the UI is responsive while the Process method is runnind. Here’s XAML code:

Code-behind the main window consists of Click event for a button that starts the process and UpdateUI method.

Process method is started as a new Task to keep the UI responsive. UpdateUI method must have signature consistent with CallBack delegate defined in Calculation class as this method is used as an argument in Process method.

Events
Concept of events enables a programmer to use a kind of notification system between objects. To depicts that I prepared small program that imitates a wallet and adding money to it. Here’s listing of Wallet class:

First of all it has a delegate GotSomeMoney declared that defines event handler signature. Event handler is a method that is executed when an event occurs. It takes two parameters: object sender (which is an object that fires the event) and EventArgs e  (object of an EventArgs class that holds argument that you want to pass with the event).
At the very end of the file above I declared a new class MoneyEventArgs which is derived form EventArgs class. This class has two properties that will be passed with the event.
Having these two parameters in event handler is to follow the .NET guidelines. It is not necessary but if you take a look at all the events for all of the controls (in WinForms and in WPF as well) you’ll see that they follow the same guidelines.
Now, if you analyse setter for Money property in Wallet class you will notice that FireEvent method is executed in some particular circumstances. This method takes one integer argument. Now, if we move on the the code of this method that it creates new instance of MoneyEventArgs class and assign certain values to its properties. Then, it checks if there are any subscriber for the OnGotSomeMoney event and if affirmative it fires the event with this as an object argument and that newly created instance of MoneyEventArgs class.
Now, let’s move to the UI. It has a text box to provide owner’s name and a button that initializes new instance of Wallet class. It also has a counter that displays content of the wallet and buttons that allows a user to add some money. The are disabled until the initialize button is clicked. Here’s XAML code:

This XAML code also defines myWallet instance of Wallet class. It all happens in <Window.Resources>. This instance will be available also in code-behind.
Now, let’s take a look at code-behind:

Code-behind has ThisWallet_OnGotSomeMoney method which signature is consistent with GotSomeMoney delegate in Wallet class. This method will be assigned as a subscriber to OnGotSomeMoney event of thisWallet instance by clicking Initialize button. Note, that this assignment is achieved by using ‘+=’ operator. To avoid clearing all subscribes it is not possible to use ‘=’ operator event. You can only subscribe to event by using ‘+=’ or unsubscribe by using ‘-=’ operator.
ThisWallet_OnGotSomeMoney method takes some values from sender and MoneyEventArgs and creates some strings that will be displayed in a message box when the event occurs.

Understanding all of these concepts required to be quite focused and multiple reading or watching of the sources I had available. If I were to recommend something that helps to understand these aspects of programming here are some links:
Jesse Dietrichson: https://www.youtube.com/channel/UCiA3tURI8dwCOUzCeM90c2g
https://www.youtube.com/watch?v=8e2GEFNctwQ&t=1466s

.NET Interview Preparation Videos
https://www.youtube.com/channel/UCHI5xgQujSyqz_UyKdLFaqw
https://www.youtube.com/watch?v=ifbYA8hyvjc&t=416s

All of the code presented in this post can be found here:
https://github.com/mickaj/DelegatesLambda
Feel free to test it!

That’s it for today. Next, I will post something about interfaces. Hopefully, shortly…
Regards, Michal

.NET programming basic course

Hi!
As I had mentioned in one of my previous posts I attended a programming course dedicated for C#/.NET beginners. The course was organised by polish IT leader Comarch (at the end of this post you will find a link to the course on their website).
I have to say that most of the topics presented during the course were nothing new to me. But, it’s completely different than learning on your own no matter if it’s from a book or YouTube course or lecture. Having that possibility to ask questions and get instant answer is the biggest advantage. Sometimes, you think that you might have not understood something you ask a question to clarify and you get an affirmative answer –  that’s a confidence boost. That gives you that feeling that you’re on the right track. You can’t get that any other way than face-to-face learning experience.
What’s more that improves the quality of the course is the fact that it was mostly all time practice. The theory part was more of a brief introduction to the topic than a lecture. All important things were presented with an example and tested by students ourselves.
After completing the course I have one advice for anyone who wants to get into programming: be extremely careful when learning online. Some of the learning materials are not prepared with that mindset that someone who’s going to learn is absolute beginner. They tend to go shortcuts, don’t pay attention to details which denies learners to fully comprehend the knowledge. And sometimes they teach bad habits (for instance I have not heard before the course about the ‘private field, public property’ convention).
What I learnt during the course and I find most important for me at this stage is deeper insight into class inheritance and polymorphism.
I am pretty happy with the course but still there were some disappointments. I was really hoping to get some more details about such aspects as interfaces, data-binding and MVVM model. We talked a bit about interfaces, the tutor showed us an example of data-binding and he said few words about MVVM. But I was simply hoping for more.
Generally, I find the course much beneficial for me and I will surely continue with courses from Comarch. The course ended with issuing a certificate. That’s my first 🙂
Thanks, Michal

Programowanie .NET – kurs podstawowy (Comarch)

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)

Localising your application

Hello!
Some time ago, while working on an abandoned project (which, I have to admit honestly, turned out to be too laborious and complicated for me at that point) I had worked out a method to localise the program using XML files. That worked perfectly okay but only recently I have that there are way easiest methods to achieve that.
Let’s start with XML method. Available languages have a unique file with all strings stored in. The file is organised as follows:

As you can see each window has a specific section in XML file, and only this section will be loaded when a window is displayed. Every window has a method which loads all related strings:

Drawbacks of this method are clearly visible: you have to write a method which will load all strings from XML file. And you have to be extremely careful not to omit any text you want to display. It worked but not effectively at all.

There is other much simpler method which I found at AltControlDelete.pl. It uses resource files and System.Globalization. General idea is that you create individual *.resx file for each language: Lang.resx for default (English) language and Lang.xx-XX.resx, where xx-XX is the name of a culture (for instance, pl-PL for Polish). What’s important is that access modifier for those files must be set as public as shown below.

lang_resx
These files must be stored in one folder (let say “Languages”). Now, you need to include them in your source code and you’re ready to use these strings in your code:

To use it with XAML you need to add appropriate namespace to Window element in XAML file:

Now, to switch between languages you need to change Culture in your process:

Of course, you need to build your app in a way that user has the possibility to switch between languages as he intends.

That’s about it. The method with *.resx files is much simpler and most of all quicker and to some point less prone to omissions and mistakes. Of course, there are other methods (for instance, Mulitilingual app toolkit  from Microsoft) but this one seems to me that is easy enough and does not require any add-on or third-party software other than Visual Studio).

This post is based on articles available at www.altcontroldelete.pl by Jerzy Piechowiak.

WPF TUTORIAL – APLIKACJE WIELOJĘZYCZNE
TWORZENIE APLIKACJI WIELOJĘZYCZNYCH Z C# I ASP.NET W VISUAL STUDIO

 

MakeNoMistakes 1.1

Greetings!

I have just finished the application introduced in previous post. To remind what the application is about: it is an implementation of a classic game Minesweeper. My addition to the idea is that once you click on a mine you have one chance to disarm the mine by solving small equation (addition or subtraction).

Here are links to ClickOnce installer and source code. As usual the code was written in MS Visual Studio.

ClickOnce installer (*.ZIP)
Source code (*.ZIP)

One note before you try it out – don’t mind the graphics. I am hopeless at drawings.

Enjoy!

MakeNoMistakes – my implementation of a classic

Hello All,
It has been a while since my last post in which I announced ‘another small app’. It is now time to publish its first version. Generally, it is another version of small game which is distributed with MS Windows and it is about finding mines. The app I have written is slightly different. It gives a player a possibility to disarm a mine if it is found by right clicking. In classic minesweeper it is possible to click with both mouse buttons to uncover all adjacent tiles. In my app it can be done by hovering a tile for a short moment. In this case uncovering the mine will result in an explosion and therefore the game ends.
This is the first version. It is not finished, but I would say it is 95% complete. What is missing is possibility to play a game on custom tile-board and a hall of fame (and nice graphics, but I am not an artist at all). Right now I am publishing only an EXE file (in a ZIP archive). Source code will be published when the application is completed.
Thanks, Michal

MakeNoMistakes (*.ZIP)

Dynamically generated buttons

Aloha!
Currently, I am working on another small app which I will present here shortly. Its function will be disclosed later as that fact is of no importance to this post. What is important is that some buttons the app will create automatically depending on some user settings. The buttons will be arranged in, let’s call it excel-style, in a table with equal size cells. So, the buttons need to be generated in a loop. That seems to be an easy task, but it becomes a bit trickier if you want them to perform different action. Here’s how to do that.

The code above shows how to generate the buttons with individual action performed by each button. But the solution above requires you to know how many buttons your program will create and still manually write separate switch/case instructions for each but. Tricky, but in some cases might be enough.

If it isn’t enough C# gives you opportunity to create actions delegates and store them in a dictionary.

These are two approaches to dynamically created buttons with individual actions for each button.

This post has been compiled from:
http://stackoverflow.com/questions/1434282/how-do-i-create-5-buttons-and-assign-individual-click-events-dynamically
http://stackoverflow.com/questions/33107026/dynamic-switch-cases
http://stackoverflow.com/questions/8414930/is-it-possible-to-declare-generic-delegate-with-no-parameters