Method parameters – overview

Syntax of C# enables multitude of way how to pass parameters into a method. The most basic way is to provide a parameter type and name. This will enforce that whenever this method is called this parameter must be supplied and the method will produce a result based on that. However this is not the only way, and surprisingly (at least for beginners) C# offers quite wide range of customisation of method signatures.

Optional parameter
A parameter can be optional, and in case it is not passed in a call its default value will be used.

In this case there are two things to be aware of:
i) optional parameters must be at the end, any other parameter cannot be after optional (a compiler will not allow that);
ii) if a method with more than one optional parameter is called the order of them matters, so in the example above if first optional parameter is to be provided, the second is to be omitted the you simply call the method without the last one which will take its default value:

However if one wish to provide only second parameter and use default value of the first optional parameter one must pass it as named parameter:


Reference parameters
In .NET there is distinction between value types and reference types [more]. So generally objects are passed by reference (as they are reference types), primitive types are passed by value (as they are value types, as well as structs). This means, in simple words, that changes a method do to an object will be visible outside. That doesn’t happen to a value type. The ref keyword allows us to declare in method’s signature that a parameter is to be passed by reference (even if it’s a value type).

Let’s consider the above code: if the RefParam() is to be called it will expect a reference to an integer variable which will be modified inside the method and saved to a reference. It will not accept hard-coded value. Note that the ref keyword needs to be present in both: method’s declaration and method’s call.

The above code will output value of n variable which is now increased by the RefParam() method.

There are two more ways to pass a parameter by reference: the in and out keywords. The former enforces that the parameter is not modified inside a method, the latter enforces that the parameter is set inside the method.

So as you can see a compiler will not allow any code that would potentially change value of reference parameter with in keyword. The advantage is that since it is passed by reference it will not be boxed (performance advantage) and you can clearly state at design that this parameter is not to be modified but read-only. Note that the in keyword is available in C# 7.2.

In a method which one parameter is declared as out there must be a statement that would set its value. If not a compiler would generate an error. In this case (similarly as with the in keyowrd) we have this explicit declaration that in the method we need to modify value of a parameter. Another advantage is that we can new-up a variable when a method is called:

This may be used as a way return more that one value by a method [more].

Multiple parameters of the same type
In case we want to pass unknown number of parameters of the same type we can use the params keyword.

If we want the above to work we could declare an overloaded method, however using the params keyword makes it way easier.

However, in this case we need to remember that type of this parameter must be an array (one dimensional, compiler won’t allow anything else) and it must be declared as the last parameter in a method’s signature.

That is short overview how flexible declaring a method can be. I encourage to experiment with it to get comfortable with all the possibilities C# language offers in this matter.

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.

Design Patterns #7: Template Method

Design patterns episode 7 – Template Method

This post is about template method pattern. Those who are familiar with the Head First book may be wondering where’s facade. The answer to that question is that I deliberately decided to skip the facade at this point. I will definitely come back to this, but maybe next time. Now, let’s move on to the template method.

DEFINITION

The Template Method pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
(Freeman, Eric, et al. Head First Design Patterns. O’Reilly Media, Inc. 2004) 

What the above mean? It means that the pattern is built on base abstract class which has a public method which defines our algorithm by invoking in intended order some other methods which may be overridden by subclasses. The algorithm’s member methods may provide default implementation of be abstract forcing the subclasses to provide their own unique implementation.

EXAMPLE
Most of the examples you can find is based on preparation of pizza, coffee etc. And they’re really good. Pizza for instance: when you’re cooking a pizza no matter what style you basically do the same: prepare dough, add sauce, toppings, put it into oven and cut. That’s the algorithm. But you certainly do different dough for American pizza and for traditional Italian pizza, you add different toppings for vegetarian pizza and for meat pizza – and that’s the where we may want to override our sub-methods of the algorithm.

The code below will not be about pizzas, it’s going to be a generic code that does nothing but show how the pattern may be implemented.
Let’s take a look at our base class:

As you can see our TemplateMethod() is not marked as virtual therefore it cannot be overridden – this is the skeleton of the algorithm. In its body this method invoke all member methods – subOperations from 0 to 3. Interesting thing is that the last member method will be executed only if a condition is true. This is called a hook. This is one way to alter the invocation list of the algorithm. You don’t need to use is but it’s good to know. Besides that we have combination of  methods with default implementation, abstract methods and those you cannot overwrite. In our case only one methods needs to be implemented in a subclass – let’s take look:

So, our concrete implementation overwrites one method with implementation in  base class and provides implementation of one abstract class. Simple, so let’s see how it works:

To witness the template method we instantiate new ConcreteTemplate and observe how it behaves – with optional method executed and without.

And that’s the template method pattern. The best explanation of this pattern I’ve found so far is in the Head First book but below you will find also one link to a YouTube video with Phil Japikse – you may find it useful.
Thanks for today and expect the next pattern next week.

Design Patterns: Template Method – YouTube
Source code: TXT file

Design Patterns #6: Adapter

Continuing with design patterns. Time for Adapter. This pattern is a structural pattern whose purpose is to convert interface (in a meaning of public members of the class, not necessarily interface as a programming language feature) so the class is usable with client’s code. The Head First book defines this pattern as:

The Adapter Pattern converts the interface of a class into another interface the client expects. Adapter lets classes work that couldn’t otherwise because of incompatible interfaces.
(Freeman, Eric, et al. Head First Design Patterns. O’Reilly Media, Inc. 2004)

Generally, it may be said that the adapter pattern wraps an object that cannot be used by a client and exposes an interface that allow the client to use that object. Let’s take a look at the diagram:

So, we have a client that wants to use an object that implements IExpected interface, however we already have a class that does what we need but doesn’t have a compatible interface (unsupported class). So, to solve the problem we need an adapter. The adapter will have all public members that the client expects – will implement the IExpected interface and at the same time will privately wrap an instance of unsupported class (passed in a constructor, for instance). Once the client calls the adapter, the adapter will in turn call the wrapped unsupported class and return results to the client (and if required convert them to what the client expects). And that’s it, simple as that.

EXAMPLE
Let’s take a look at code example now. We have a class that calculates area and perimeter of a rectangle. (These calculations are very simple but to give the example a little bit more depth think of them as of very sophisticated and complicated). That class operates on double type. Our client, however wants to calculate area and perimeter of squares only and operates on integers. We could i) write a new class to handle that but we don’t want to do that because we already have a class that is capable to perform such calculations (square is a rectangle after all, right?); ii) modify our client to work with the existing class, but again we don’t want to break anything elsewhere (OCP right?). That’s why the right solution here is the adapter.
Let’s compare what we have and what we need:

So, the differences are: i) types (already mentioned int vs. double), ii) method names, iii) number or arguments required for counterparting methods.
Now the adapter. First of all it needs to wrap the already existing class and set its instance by passing it through constructor; then we need to implement methods required by IExpected interface in a way that they call the wrapped object and return values converted to integers.

Let’s write a quick test:

Everything works perfectly.

Object adapter vs. Class adapter
The explanation and code example is an object adapter. This means that the adapter works with a concrete instance of adapted object. Advantage of this solution is that this type of adapter will work also with objects of classes which are derived from adapted superclass.
There is also another adapter-type pattern called class adapter. In this type you don’t need an instance of adapted class, instead the adapter class inherits from both: expected class (or interface) and adapted class. Remember that inheriting from more than one superclass is not possible, what could be done is to create new class that inherits from a class that needs to be adapted and implements expected interface. This approach may also be useful but keep in mind that it looses the advantage of composition over inheritance.

To sum things up: adapters are extremely useful everywhere there is a need to use something that can do what we need but doesn’t have compatible interface.
Plan for next week: Facade

Don’t forget to check the links below!

Christopher Okhravi about Adapter Pattern: [YouTube]
Source code: [TXT file]

Design Patterns #1: Strategy

Nau mai!
Time for design patterns. Whenever I tried to find out anything about them I encountered this pretty good explanation what are they and why we need them:

Someone has already solved your problems.

‘Head First Design Patterns’ (page 1)

And after Wikipedia:

In software engineering, a software design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine code. It is a description or template for how to solve a problem that can be used in many different situations. Design patterns are formalized best practices that the programmer can use to solve common problems when designing an application or system.

[source]

In a nutshell: common solutions to common problems. And that should be sufficient to start with first design pattern: Strategy. But, before that quick introduction to this series. It is inspired by Christopher Okhravi and his playlist. I will do basically the same: go through all design patterns in Head First Design Patterns book by Eric Freeman, Elisabeth Freeman, Bert Bates and Kathy Sierra. I have Polish edition but that does not make any difference for you, I will not give any quote in Polish (probably I won’t give any quote at all). To make this series somehow different and not to copy either the book or videos linked above I will use different examples. So, with that being sad we can cut to the chase.

Definition
Strategy defines common abstraction of set of algorithms, encapsulates them and make them reusable and interchangeable in run-time.

How is that achieved:

  1. Define abstract class or interface that has one common method which invocation will perform some action
  2. Define concretions for the above
  3. Add variable of type strategy abstraction to your client class
  4. Add method in your client class which will execute strategy
  5. Add method in your client class that will allow to change strategy

    And that’s basically it. Now, let’s move to example.

    Example
    Example given in book is a duck simulator. It uses different types of duck where actions such as quack or fly are abstracted and encapsulated into strategies. Good example in my opinion. Our example is magic box that consist of an array of 10 integers which can be displayed in console. But the way the numbers are displayed varies depending on enumeration strategy. Let’s start with abstracting the enumeration strategy:

    So, our strategy is used to return string that enumerates all numbers in given array.
    Now, let’s implement different strategies: enumerate as is (without changing the order), bubble sorted and shuffled.

    What could be done better in those three implementations is that part of the code that build output string is common so natural reaction would be to encapsulate it somehow, but please, turn a blind eye for that 🙂
    Next step – writing our MagicBox class which has an array of 10 integer, randomly generated in the constructor, private field of type IEnumerateStrategy accompanied by a method for changing the strategy, and Display() method that writes numbers to the console using the strategy.

    To test the example in application’s Main() method, we will create new MagicBox object and assign new AsIsEnumeratorStrategy, then invoke Display() method, and then assign some other available strategies and again invoke Display() method.

    So, as a result we get number listed using three different strategies. Advantages of using Strategy Pattern is that you can write as many strategies as you want without changing the class that uses them and interchange them during run-time (the definition, right?).So that’s it when it comes to Strategy Pattern. If you’re interested in next pattern (which is going to be the Observer) please come back (probably) next week. Thanks!

    Source code: download zip file

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

Inventor API: EventTimingEnum

Hi there,
Some time ago I started writing an add-in for Autodesk Inventor. That software exposes an API that allow to develop add-ins in C#/.NET. In this post I am not going to write anything specific about the project; it will neither be an insight into API specifics. I just want to give quick explanation about controlling events with use of EventTimigEnum.

Some actions in Inventor can take a bit of a while – for instance placing big component into an assembly. Therefore, it is possible to decide when custom action is performed – either before or after an event is completed.

Let’s start this demo with writing a method that will be executed when a new component is placed into an assembly:

Just a brief explanation to the code above: of course only a method with matching signature can be assigned to an event, and it is necessary to set value of HandlingCodeEnum output parameter.
Now, to attach that method to an event that fires whenever a new component is inserted to assembly you need to access Inventor instance. In this example it will be done in add-in Activate method.

Once that is done we can start Inventor and see what’s the result:



As you have probably noticed our CustomAction was executed twice. Sometimes this behaviour is desired, sometimes it’s not. Now, let’s modify our method to perform action only after the event is completed. To do that we need to check value of EventTimingEnum parameter and perform action whenever its value is what we desire.

Now, the message box will be displayed only after the event is completed. EventTimingEnum can have one of three possible values: kAfterkBefore (which are self explanatory) and kAbort. The last value can be used in case we want to perform an action when an event is cancelled – for instance, when opening an assembly with lost reference user can decide to cancel opening.

It is also important to mention that not all events in Inventor are fired both kBefore and kAfter. Most of them are but you need to be aware that there are exceptions from that rule.

So that’s it if it comes to EventTimingEnum.
Unfortunately, there is not much about writing Inventor add-ins in .NET. What I recommend to check is first and foremost this GitHub repository:
https://github.com/ADN-DevTech/Inventor-Training-Material
It is complete course on Inventor API. There are presentations and code examples (in VB.NET and C#) for each chapter.
The other thing is class diagram delivered by Autodesk which comes with Inventor SDK installation. It can be found in Autodesk/Inventor/SDK/DeveloperTools/Docs in PublicDocuments on your C drive.
Regards, Michal

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