Posted by: rhwilburn | February 5, 2009

Why we Blend & Custom combo boxes

I have been sceptical of Expression Blend for a while now. I have found that it is was a marginally better designer than Visual Studio and I didn’t see what the fuss was about. Yesterday I found out a massively powerful feature that now I wouldn’t develop WPF without. The feature I am talking about is the ability to copy existing styles from framework controls such as  a combo-box and change them. This is best demonstrated at the following blog: http://www.designerwpf.com/2008/10/01/how-to-use-a-listview-or-datagrid-in-a-combobox-drop-down-without-a-line-of-code/. For that blog tutorial you don’t need to add a reference like the tutorial asks if you aren’t going to use a datagrid control.

One thing to be careful of is that there will be two item presenters in the template. If you are like me and wanted to make a customizable combo-box drop down but also have the selected item area update then you will need to make your control isEditable=true and isReadOnly=false. This will use the opposite ItemPresenter once isEditable is changed to true. This initially gave me a fright thinking that I would not be able to use isEditable.

If multiple selection is wanted in your custom combo box you can try: http://jobijoy.blogspot.com/2009/02/simple-multiselect-combobox-using.html

Posted by: rhwilburn | January 28, 2009

Docking WPF controls to right or bottom of a Canvas

When first learning WPF one thing that stumped me was docking controls to the right hand side of a canvas. As I understand WPF layouts, the only default WPF control that allows controls to overlap is the canvas layout control (See comments about a correction here. The canvas control is not the only control that allows items to overlap). This is why I was forced to use the canvas layout (as I wanted the ability to place controls over the top of each other).

The way to solve this issue was to use a multibinding and a multibinding converter. I have provided a code sample below showing a treeview control that is docked to bottom right side of a wpf window.

<TreeView x:Name="Menu" DataContext="MenuData" Height="350" Width="220">
  <Canvas.Left>
    <MultiBinding Converter="{StaticResource RelativePlacementConverter}">
      <Binding ElementName="MainCanvas" Path="ActualWidth" />
      <Binding ElementName="Menu" Path="ActualWidth" />
    </MultiBinding>
  </Canvas.Left>
  <Canvas.Top>
    <MultiBinding Converter="{StaticResource RelativePlacementConverter}">
      <Binding ElementName="MainCanvas" Path="ActualHeight" />
      <Binding ElementName="Menu" Path="ActualHeight" />
    </MultiBinding>
  </Canvas.Top>
</TreeView>

public class RelativePlacementConverter : IMultiValueConverter

{

#region IMultiValueConverter Members

public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)

{

double? screenWidth = values[0] as double?; //parent width

double? menuWidth = values[1] as double?; //own width

if (screenWidth != null && menuWidth != null)

{

return (screenWidth – menuWidth);

}

return 0.0;

}

public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)

{

throw new NotImplementedException();

}

#endregion

}


The previous code uses the width and height of the treeview control called Menu and subtracts that from the width and height of the canvas called MainCanvas. For more usecases or more depth on how to implement a multibinding I recommend the following: wpf-tutorial-using-multibindings.

I would recommed using multibindings when a value needs to be result of a combination of other values. There are other ways around this issue without using a multibinding. Links to APIs to avoid multibindings are avalible at: http://marlongrech.wordpress.com/2008/02/10/embed-code-in-xaml/. I like the idea of avoiding multibindings as they take a bit more effort that should be required for simple scenarios like this blog post, however I am also sceptical of alternatives because they don’t yet seem to leverage the power of code behind the way that the multivalueconverter allows.

Posted by: rhwilburn | January 21, 2009

Linq Anonymous return types

I have decided to make a post about LINQ anonymous types with respect to typing after talking to some colleagues. Below I compare 2 LINQ statements, the first being with an anonymous type being returned, the second with a specified type being returned.

Anonymous type:

IList<Window> windows = new List<Window>();

 

var query = from window in windows

            where window.Visibility == Visibility.Hidden

            select new

                     {

                         Visibility = window.Visibility,

                         Title = window.Name

                     };

 

image

Specified Type:

IList<Window> windows = new List<Window>();

 

var query = from window in windows

            where window.Visibility == Visibility.Hidden

            select new myType

                            {

                               Visibility = window.Visibility,

                               Title = window.Name

                            };

 

image

Comparing the two return types shown in both of the images, we can see that both return the same data. The thing we cannot see is that an anonymous type is scoped to the method that the LINQ statement is in. This means that we can’t pass query off to another method unless we extract the data we want to a non anonymous type.

Posted by: rhwilburn | January 15, 2009

C# variable naming

From working in a team environment, I have learnt of a number of different ways of naming variables. Reading this post it could be thought that variable naming schemes are purely preference, however I believe that there are some arguments against certain schemes. Take for example:

        private String str;

        public void Method1(String str)

        {

            this.str = str;

        }

 

If you use a plugin called Resharper  like I do then the method input is highlighted because it hides str. I have more of an issue with the following potential mistake:

        private String str;

        public void Method1()

        {

            this.str = str;

        }

 

The previous code is still valid with the compiler, however it is clear that str is not going to be populated, however a tool such as resharper will not make you aware that the this.str is never assigned.

The approach that I use for code sample 1 would be:

        private String _str;

        public void Method1(String str)

        {

            _str = str;

        }

 

The underscore ‘_’ is used for member/class wide variables. If we are to replicate code sample 2 with the underscore naming scheme we will get the following result:

        private String _str;

        public void Method1()

        {

            _str = str;

        }

We can clearly see that this code will not compile. We can also observe that the underscore notation is more compact by not requiring the ‘this’ keyword.

Another two reasons I like the underscore naming convention are:

 

  1. Intellisense grouping. Press underscore key and intellisense will group all member variables together.

  2. No confusion as to the availability of a variable. If it has underscore it is available class-wide. If it doesn’t it is only available within that method.

I have seen other people use m_VariableName but I think that just using an underscore is better because it is shorter, and the intellisense is grouped better because it is at the start of the intellisense list. Another alternative naming scheme involves putting the type in the variable name. I would advice against this because tools like resharper can tell a user what type a variable is in design time, and implicit typing will likely destroy the naming scheme.

Posted by: rhwilburn | January 9, 2009

List Conversion

One of my favourite use cases for lambda expressions in .NET is converting lists. Take the following code as an example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Windows;

 

namespace LambdaComparison

{

    public partial class Window1 : Window

    {

        public Window1()

        {

            InitializeComponent();

 

            IList<Person> people = new List<Person>();

 

            Example1(people);

            Example2(people);

        }

 

        public void Example1(IList<Person> people)

        {

            var names = people

                          .Select(item => item.Name).ToList();

        }

 

        public void Example2(IList<Person> people)

        {

            var names = new List<String>();

 

            foreach (var person in people)

            {

                names.Add(person.Name);

            }

        }

    }

 

    public class Person

    {

        public String Name

        {

            get; set;

        }

    }

}

From using this approach for converting lists between types I have found that it leads to more readable code, as it is one line rather than many.

One other thing that is worth noting and is very important tip when using LINQ or lambda expressions, is that the return type is IEnumerable<T>. Often when using LINQ etc it is common for people to expect a list or use the "var" keyword. The var keyword is not actually a type but rather is implicitly typed which means that the compiler infers/computes the type based on the right hand side of an assignment. I usually use var but i had issues with more complex LINQ statements until I realised how to understand what the var keyword was representing and how it was being deduced (which is not immediately obvious for beginners with many LINQ statements). LINQ also offers the ability to create annonymous types which provide challenges in the area of non implicit typing.

Posted by: rhwilburn | December 6, 2008

Dependency Injection as a tool for Reactive Programming

A few posts ago I talked about Reactive Programming and how I have decided to make it my primary concern architectually when developing. I recently read on the ninject site that an advantage of using a dependency injection framework such as ninject is that depenencies can be inspected, modified and be conditional. This is interesting, as this sounds like it offeres advantages comparable to data-binding. Being able to evaluate functions and relationships between code modules or elements is definately positive in my book because it allows us to have more ability to reason over information we have already provided.

A real world example, that I have seen demonstrated, could be as follows:

if an application is being executed then provide an implementation of a service that calls to say flicker, or amazon etc.

at design time we still want our visual studio or expression blend to work, and it would be nice if it had some data to display. We can do this by injecting a different depenedency link. This link would point to a dummy service that would just display data to help us in the designer views.

For more depth see: http://jonas.follesoe.no/YouCardRevisitedImplementingDependencyInjectionInSilverlight.aspx

While this could be done without dependency injection, code would start getting consolidated and repeated leading to code smells (ie bad practices). It is also worth stating that the example of using a webservice and specifying different implementations is quite a simple example. With that said I think the true power of Dependency Injection not only leads to better plug-ability of code modules but also the reasoning over these bindings.

Posted by: rhwilburn | December 6, 2008

The Singleton Pattern

One of my favorite gang of four patterns is the singleton pattern. The singleton pattern is a “Gang of Four” design pattern which is commonly used for maintaining one common instance of an object that is widely accessible. For C# implementations of the singleton pattern I previously used the 4th pattern on the following site: http://www.yoda.arachsys.com/csharp/singleton.html. Recently however I have come to find issue with the singleton patterns in C# on two fronts. The first front being WPF view models. The second being from a Test Driven Development (TDD) perspective.

  1. The first point I have about the singleton pattern is that if you require the ability to subclass an existing class it becomes an anti-pattern. An example with WPF could be the requirement to adopt depenedency properties on a class. You could then argue that a class could be used to provide a single instance of the object. This would work for C# code, but it is problematic for XAML.  It is possible to maintain a single instance of a class in XAML with the ObjectDataProvider tag but then you would need to find that instance from the pages resources (usually a resource dictionary).  As I mentioned in a earlier post, it is important to me architecturally that XAML controls/resources are not directly referenced unless absolutely necessary.
  2. The second point is possibly more globally recognized, that singleton pattern is an anti-pattern when trying to unit test a class. For more on this you can google with the keywords of “singleton unit test” or check out the following blog post: http://codebetter.com/blogs/jeremy.miller/archive/2005/08/04/130302.aspx

The singleton is still a great concept and a great tool to have in a developers arsenal but now I take a different approach by using an IoC (Inversion of Control/Dependency Injection) container called ninject which provides a Singleton attribute which provides uses the IoC facilities to maintain a reference to a single instance of an object. I feel that this approach will play well with WPF databinding because I believe the attribute will allow calls to be directed at the class without having knowledge of the factory maintaining the instance (Note: yet to confirm this in practice). I believe that other developers have opted for adopting service locators instead of singleton patterns. A blog post about the argument of IoC vs Service Locators is provided here: http://kohari.org/2008/06/18/playing-nice-with-service-locators/.

Posted by: rhwilburn | December 5, 2008

Reactive Programming

The thing that made me jump into WPF and adopt a new fundamentalist regime of XAML pure-ism was a talk by
Ivan Towlson in late August on Reactive Programming. His slides are available here: http://hestia.typepad.com/flatlander/files/thinking_in_wpf.pptx

An example of Reactive Programming as Ivan explained that we use often is the SUM calculations in Excel. When we change the inputs into that sum calculation the calculation is retained and re-executed. The counter example (ie not using a reactive style) would be where you supply the sum equation and when displaying the sum value, your equation is not retained and only the resulting value is displayed. This means updating inputs of the sum don’t affect the sum value. I suggest checking out wikipedia for a better introduction:  http://en.wikipedia.org/wiki/Reactive_programming

To become a Reactive Programmer. I have the following suggestions/tools

  • Put as much display logic into XAML as possible as it is declarative (there is a bigger learning curve doing it this way as XAML is frustrating to learn)
  • Use as much databinding as possible. To do this you should adopt a view model. This allows you to update view data in the view model which will update the view. If you do this properly you should be able to never reference a XAML item by name from non XAML code(ie C# in my case).
  • Be mindful that LINQ is a staic one way action that can be databound but would require events to refresh and would only be a one way binding. I recommed Bindable LINQ to get around this problem.  http://www.codeplex.com/bindablelinq
  • In reactive programming, when displaying view data from the view-model I am of the opinion that Databinding is good. Events are bad. I think this point is fairly obvious. The most immediate benefit is that it simplifies code by reducing the number of lines required. The second benefit that comes to mind is the ability to potentially copy/serialize/insepect a binding for use elsewhere or for storage for later use.

As software devs we should be trying out best to reuse all of our code and reactive programming provides a great mindset for doing this. Unfortunately some of the xaml tags that I use for reactive programming are lacking in Silverlight, so I am doing my projects in WPF and am hoping in the future that Silverlight supports more WPF. A great example of a reactive WPF application that wouldn’t work in silverlight is the quake example which I provided in my first blog post.

Posted by: rhwilburn | September 30, 2008

Thinking in WPF

When first starting to develop in WPF most users will come from a background such as winforms where it is common practice to use an MVP approach to UI’s where a UI is “dumb” and is modified by controlling underlying logic. Controls were often chosen by how they looked as modifiying their look usually required overriding. Often code was just left in the code behind of the UI component which is even worse.

The WPF way of thinking tends to be that the visual appearance of a control doesn’t really matter as it can be modifed easily in XAML with a contentTemplate. Take the following pseudo code example which demonstrates how to make a radio button look like a normal button.

<RadioButton>

<RadioButton.ContentTemplate>

<Rectangle … />

</RadioButton.ContentTemplate>

</RadioButton>

Which you might then ask what indicates the control that should be chosen for a task. The answer lies in the underlying datatype of that control and the behavior that control provides. For example a game canvas can be made by using a listbox, as it contains a representation of a list of visual game items. For an example of this see the quake example linked to in the first post. Another example of this way of thinking presented itself to me the other day when I made 3 toggle buttons. After placing them I realised that I wanted to only have one button selected at a time. To do this I chose to instead use Radio buttons. Radio buttons are able to belong to a group which allows only 1 of them to be selected or toggled at a time. I then used a content from someones blog post about re-themeing a button control and just used that same template over my radio buttons.

Posted by: rhwilburn | September 20, 2008

First Post – Learning WPF

I have finally decided to make a blog because of all of the interesting things I am learning with .NET 3.5 and WPF.

Learning the WPF way of doing things can be quite challenging as you need to drop the poisonous mindset of Winforms to not fall into WPF anti-patterns. I recommend the following links and tips to learn WPF. Follow these and you will learn WPF quicker that I did. I must confess that i fought the idea of these concepts initially but I couldn’t achieve a reasonable design in terms of architecture with out them. Life is miles easier having taken the WPF plunge.

http://www.mindscape.co.nz/blog/?p=69 This tutorial shows how the underlying behavior of a control is more important than how the control renders items. It also shows datatemplates which remove the need to extend controls to change the appearance. It is important to consider that listbox provides selectable item behavior and it binds to a list collection. How it displays data is irrelevant as it can be changed.

http://www.nikhilk.net/Silverlight-ViewModel-Pattern.aspx (This tutorial shows how the traditional MVP is better replaced by a new model. The first links code sample generally follows this design pattern.

I should also point out that I have seen many people try to extend WPF controls. This is not particularly a great idea as you don’t seem to be able to extend multiple levels of inheritance. What you are better to do is to databind your Xaml control to an BaseClass such as Quake (see the first link for example). Then you can extend Quake, by making a class BigQuake. If you add BigQuake to the list that is the datacontext of the listbox, you can use a complex object model with many levels of inheritance without extending any XAML classes. This seems to be a common issue bought up by people first learning XAML because the mindset tends to be to extend a control to change its behavior. This should be a last resort in WPF.

Resource dictionaries can be used to provide centralized themes for your application controls.

A common usecase for businesses to migrate to WPF is the concept of streaming User Interfaces. This is due to the fact that XAML is an XML syntax so it is easily serializable. If you wish to do this, you really must attempt to embrase true WPF thinking otherwise the task will not be simple.

DependencyProperties seem like a nightmare when first learning WPF, there is no Textbox1.Text anymore. Its Textbox1.SetValue(TextBox.TextProperty, “text goes here”); . It is important to learn depenedency properties. A good link to do this is: http://blog.paranoidferret.com/index.php/2008/03/07/wpf-tutorial-introduction-to-dependency-properties/
Another point of interest for people migrating to WPF from Winforms is that you should endevour to put as much as you can into XAML. Almost anything in the codebehind of a WPF Usercontrol tends to be due to laziness of not learning the proper XAML to do it. I do concede however that it is not always possible to avoid using code behind. I am for example at a loss as to how to bind my code to zoom to the current Mouse position with out resorting to code.

« Newer Posts

Categories