WPF Styles (quick guide)

Styles provide a good way of providing a richer feel to your UI. They provide ways to change the look and feel of controls within the UI and establish UI behaviour such as changing the background colour based on some properties or bindings. You can create styles either in code or in xaml. Xaml is the conventional way and in this article I am going to concentrate mostly on how to define and use styles in xaml. Below gives a indication of how a style is declared:

<style>
 <!-- styles can contain a collection of setters -->
  <setter>
  </setter>
 <!-- styles can contain a collection of triggers -->
  <style.triggers> 
  </style.triggers>
</style>

Creating a style is straight forward using the style tags and together within these tags you can provide a list of setter tags which allow you to set values for certain properties. For example within the style tags I can have

<style x:Key="red_background_style">
 <setter Property=”Background” Value=”Red”/>
</style>

So when I apply this style to a control it will change the background of the control to red. If I apply the style to a button control, the button’s background will be red.

There are also other types of setters, such as EventSetters which instead of setting property values it sets event handlers for certain events. The example below shows how the event setter tag maps the mouse_down_handler to be called when the MouseDown event occurs.

<style>
  <eventsetter event=“MouseDown” handler=“mouse_down_handler”>
</style>

Now in general a style is a collection of setters and/or eventsetters and also triggers which I will talk about a bit later. Let’s put together a style and show the xaml. I’m going to apply my style to a button to give it a different look and feel.

<Button Height=“25” Name=“sample_button” Width=“50”>
   <Button.Style>
      <Style>
         <Setter Property=“Content” Value=“fxmax's button”/>
         <Setter Property=“Background” Value=“Green”/>
      </Style>
   </Button.Style>
</Button>

In the above example I have defined a style within the control but I could also have declared this style in a resource collection, and given the style a key this is a name and in my button control set the style property to this style using the key. Putting styles in resource collections and keeping them in a separate file is a good idea. I can then use them in all views for my applications by referencing the resource collection in my xaml files. I can even set the style to be the default style for a particular control using the Target_type property of the style. See this example:

<Window.Resources>
   <Style TargetType=“Button”>
      <Setter Property=“Content” Value=“Style set for all buttons” />
      <Setter Property=“Background” Value=“Red”/>  
   </Style>
</Window.Resources>

Here I have placed the style in the windows resource collection in my Xaml file for my view but set the target type property to be a button. Now all buttons in my view will have this style. If I wanted to have one button in my view to be different I could create a style that is based on the above style but override or add new styles. I can do this with the BasedOn property.

<Window.Resources>
   <Style x:Key=“baseStyle”>
      <Setter Property=Content Value=“base Style”/>
      <Setter Property=“Background” Value=Green/>
      <Setter Property=“FontSize” Value=“15” />
      <Setter Property=“FontFamily” Value=“Arial” />
   </Style>
   <Style x:Key=“newStyle” BasedOn=“{StaticResource baseStyle}”>
      <Setter Property=“Content” Value=“new style: inherited”/>
      <Setter Property=“Background” Value=“AliceBlue”/>
      <setter Property=“FontStyle” Value=“Italic” />
   </Style>
</Window.Resources>

Triggers

When you start putting triggers into your styles then things start to become interesting. Triggers allow you to change style properties when certain conditions occurs. There are five types of triggers that you can have Property Trigger, Multi-Property Trigger, Data Trigger, Multi-Data Trigger

Property Triggers
This is a trigger that monitors a single property and activates when that property meets the condition of the trigger. For example below is a simple trigger that changes the font colour when the mouse is over the control.

<Style.Triggers>
   <Trigger Property=“IsMouseOver” Value=“True”>
      <Setter Property=“Foreground” Value=“Black” />
   </Trigger>
</Style.Triggers>

Multi-Trigger
This is much like the property trigger but monitors more than one property, an example below shows just how this works. The style checks not only if the mouse is over the control but also if the button contains a value of ‘a’.

<style x:key=“buttonStyle” TargetType=“Button”>
 <MultiTrigger>
      <MultiTrigger.Conditions>
        <Condition Property=“Content” Value=“a” />
        <Condition Property=“IsMouseOver” Value=“True” />
      </MultiTrigger.Conditions>
      <Setter Property=“Foreground” Value=“Black” />
 </MultiTrigger>
<style>

Data Triggers and Multi-Data Triggers
The data triggers are much like the property triggers but the difference is that the data trigger monitors the value of bounded data, whereas property triggers deals with property values. Below is another example of a data trigger.

<style>
 <style.triggers>
    <DataTrigger Binding=“{Binding Data.Count}” Value=“0”>
       <Setter Property=“Background” Value=“Red”/>
    </DataTrigger>
 </style.triggers>
</style>

This is the end of the article hope this gives some insight.

WPF Data Binding (The quick guide)

Here is a quick and brief guide to WPF data binding, hope it helps those new to WPF.

Most applications have some sort of internal data which they want to show in the UI for the user to view. So for example let’s say we have a sales systems which holds data about its customers. So I would expect a customers class that would hold the details of each individual customer, and this would be mapped to the UI somehow so when the users wants to see information about a particular customer they can.

class Customer
{
   public string Name { get; set;}
   public string Address { get; set; }
   public string Phone { get; set; }
}

In the WPF world the mapping to the UI is done using data bindings, as this is a good way for the UI to be mapped to actual objects, and to enable the UI to be refreshed when data is changed either through the user or the system.
Below is an example of how we can create a binding through code between a text box and our customer object above and show the name of the customer in that text box.

Customer customer = new Customer("Bob", ...);
...
Binding binding = new Binding();

//set the source for the data binding.
binding.Source = customer;

//set the property which will provide the value to the ui.
binding.Path = new PropertyPath("Name");

//set the control object and its property to be populated in the ui.
nameTextBox.SetBinding(TextBox.TextProperty, binding);

  • source = is the object where the data is coming from.
  • path = establishes the property to retrieve the value from.
  • target = identifies the instance and property data is going to. 

Things to remember about binding:

Target property must be a DependencyProperty 

Source can be any object, the named property must be a valid property that returns a value.

How to update the UI when the source object changes.

The object should implement the INotifyPropertyChanged interface. This interface fires an “PropertyChangedEvent” event when the property has changed; usually through the property setter. The WPF engine is notified of the change through this event and updates the UI accordingly, by re-evaluating the binding.

Here is our Customer class updated to implement that interface.

public class Customer : INotifyPropertyChanged
{
  private string _name;
  public string Name
  {
    get { return _name; }
    set { _name = value; OnPropertyChanged("Name"); }
  }

  public event PropertyChangedEvent PropertyChanged;

  private void OnPropertyChanged(string property)
  {
    PropertyChanged temp = PropertyChanged;
    if (temp != null)
    {
       temp(this, new PropertyChangedEventArgs(property));
    }
  }
}

Flow of Information

In bindings it is possible to set the binding mode which determines the direction of data transfer. We have four modes, “One Time”, “One   Way”, “TwoWay”, “OneWayToSource”

When data exchange happens

We can also set when changes should be applied to the source, so this when the user is entering data on the UI, let’s say for example a text box, we can dictate when the data actually gets copied to the source object that the text box is binded to.  This can be done through the UpdateSourceTrigger property. You can set three values.

  • LostFocus: when we copy when the user moves off the control.
  • PropertyChanged: when target value changes.
  • Explicit: copy only when asked.

Creating Bindings in XAML

<StackPanel>
  <StackPanel.Resources>
   <me:Customer x:Key="customer" Name="Bob" .../>
  </StackPanel.Resources>

 <label>Name</label>

 <TextBox x:Name="nameTextBox">
  <TextBox.Text>
    <Binding Source="{StaticResource customer}" Path="Name" />
  </TextBox.Text>
 </TextBox>
</StackPanel>

The WPF Interview

Since I added an entry to the blog for C# it only makes sense to add a page foWPF types of questions.

  • What is a dependency property
  • What is a style and a template
  • Visual tree vs Logical tree
  • Binding, what is it and how does it work.
  • Explain Visual, UIElement, FrameworkElement
  • Explain the importance of INotifyPropertyChanged interface.
  • ResourceDictionary
  • UserContols
  • Converters what do they do and how do they work.
  • Routed Events Vs Commands
  • Bubbling events and Tunneling
  • WPF 2 pass layout engine.
  • Container controls grid, stacks extra
  • Custom contols
  • Data template vs hierarchicalDataTemplate
  • ItemsControl vs ItemPresenter
  • ContentControl vs ContentPresenter
  • Explain Triggers and how you can set them up
  • Difference between MVVM / MVC / MVP
  • Explain purpose of the dispatcher
  • Explain how you can use the Background worker thread.
  • Attached properties.
  • Prisim explain what is how does it work
  • Unity container what does it do
  • Explain the concept of SOLID
  • What are the different ways you can register objects with the unity container.
  • What are regions in prisim
  • What is CAB stand for.
  • MEF container
  • WPF performance tuning.

There are a lot more and I hope to add to list and if people want it, then I may also post answers to these as well.

Microsoft Visual 2012

I downloaded Microsofts visual 2012 this week, and to be honest it’s got a very different look and feel to 2010, and I am not sure if I like it. It comes by default all white theme with hardly any colours, the icons in the solution explorer and the toolbars have changed, the entire image and logo of VS has changed. I think it might take a little while getting used to it then I might start loving it, I will come back in a few days to give a proper review and verdict.

Having said all that I have noticed some nice new features, in the xaml when I use a hex code for a colour the editor highlights the code with the actual colour. I must also mention the parallel build when you compile take a look at task manager you will see numerous msbuilds running. This I love as it speeds my build since it uses my multi-core system.

Watch this space…

The C# Interview

I guess interviews can come in different formats. It is either written, spoken, coding, etc. The ones I hate is where they give written interviews, and you have to write an answer to a question where you could write a lot of things, and you do not know what they are really looking for.

Anyway to help those out there I have compiled a list of c# interview questions: (Some of these are not direct questions but also topics that you should be aware.)

  • Difference between a reference type and value type.
  • Where is the memory of a reference type allocated and that of the stack.
  • Difference between an abstract base class and an interface.
  • How to sort an array.
  • What is special about the string literals what should you be aware of them.
  • When you declare a const variable what does the CLR do under the hood.
  • How is a dictionary implemented under the hood.
  • When should you implement the GetHashCode and Equals method.
  • If you declared a struct how would the default Equals method work.
  • What is the Large Heap
  • What is a WeakReference type and when can you use it.
  • When should you call the Garbage Collector.
  • What is the difference between a Mutex and a Thread.
  • What is a Lamda expressions.
  • What happens when an exception  is thrown in the Finalizer method.
  • When do you use a Finalizer.
  • What is the IDisposable interface and what is it used for.
  • What happens under the hood when you declare anonymous methods.
  • How are objects Finalized.
  • How does the garbage collection work.
  • When does a garbage collection happen.
  • What can go into an interface.
  • Can you inherit with a struct.
  • Can you have a default constructor in a struct.
  • Difference between readonly and const.
  • What is the order of initialization Base constructor, Dervied Constructor, Static Constructor, Class initialization, Static initialisation.

There are loads more and will add more and more to this when  I get time.

ComboBox ControlTemplate

One of my clients wanted me to develop a different style of widgets on the UI. They wanted a drop down feature which had buttons and check boxes, so that effectively the users would see a collection of menus where they could turn on/off certain features of the application. There was a number of ways I could have done this and but I decided to take a combo box and change its control template to what I wanted. I could have styled the combobox but I saw a control template sample that Microsoft provide and in their documentation which pretty much does what I wanted so I took that and changed it to my needs.

I actually do create a combo style but provide a combobox template, and once you know what your doing its pretty straight forward. The comboBox basically has three parts to it the toggle button which in most cases has a drop down arrow on it, the text box, which is where users can type something if they want, and the popup which is the drop down menu that appears when users either click into it or start typing.

Now in this example I am going to make a simple ComboBox that will contain a row of check boxes like one seen below. I am going to provide my own control template for the ComboBox. This can actually be achieved a lot easier by styling the items in the ComboBox, but what I am trying to show is how easy it is to change the control template of the comboBox and although I have only done a few tweaks you can do a lot more.

I am going to provide my own down arrow for the toggle box as purely because I do not like the default one, and the purpose of it is to show you what you can do so in yours you can change it to any image you like, like a search box image.

In the control template I provide a template called FilterBoxToggleButton and in this I provide the image of the down arrow to be displayed in the ComboBox. Followed by this is the text box which is the editable part now in my sample I have disabled the text box so that users cannot type anything into it.

In order to see clearly what I have done simple download my sample.
Click here to download

Drag and Drop with ListView WPF

I found myself with the task of creating a screen where users could arrange the order of certain items. Now instead of having a crude mechanism of numbering each item accordingly I decided to opt for a more interactive way to order. I chose to show the user a list of items where they could drag and drop each item based on the required order that they wanted to see.  I decided to see what others had done and found a number of implementations on the web but none that gave me what I wanted. I wanted something quick that would allow me to rearrange the items in a list view. The most closest that I came to was Christian Moser drag and drop. Now the problem is that the code here does not show a visual item being dragged, and simply adds the same item to the list creating duplicates. What I have done in this sample is to take Jamie Rodriguez’s article about drag and drop  which shows how to do dragging and use it with Christian Moser sample and provide a ListView WPF application that allows you to rearrange items in a list and visually show the dragging being done with the mouse. I hope this helps someone trying to achieve the same thing.

There are two parts to creating the drag and drop with visual dragging. The first is wiring up the drag and drop events which moves the object when the user drags and drops something. The second is to create an adorner when the drag event occurs and update the adorner as the mouse is moved.

Part One.

First create the ListView object and make sure you set AllowDrop to true, and set the Drop, DragEnter, PreviewMouseMove, and PreviewMouseLeftButtonDown event handlers, as below.

The following is the implementation of the event handlers declared in the xaml extract above.

private void ListViewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
   _startPoint = e.GetPosition(null);
}

 

 private void ListViewPreviewMouseMove(object sender, MouseEventArgs e)
 {
      if (e.LeftButton == MouseButtonState.Pressed)
      {
          Point position = e.GetPosition(null);

          if (Math.Abs(position.X - _startPoint.X) > SystemParameters.MinimumHorizontalDragDistance ||
              Math.Abs(position.Y - _startPoint.Y) > SystemParameters.MinimumVerticalDragDistance)
          {
             BeginDrag(e);
          }
      }
 }

These method handlers get the current position of the mouse, and when a left mouse button is pressed it checks to see if the current position yields a listViewItem object then the dragging gets started.

The following code handles the movement of the listViewItem from the drag action. It moves an item in the list view and puts it at the location that you dragged it to.


private void ListViewDragEnter(object sender, DragEventArgs e)
{
    if (!e.Data.GetDataPresent("myFormat") || sender == e.Source)
    {
        e.Effects = DragDropEffects.None;
    }
}

private void ListViewDrop(object sender, DragEventArgs e)
{
   if (e.Data.GetDataPresent("myFormat"))
   {
     string name = e.Data.GetData("myFormat") as string;
     ListViewItem listViewItem = FindAnchestor((DependencyObject)e.OriginalSource);

     if (listViewItem != null)
     {
         string nameToReplace = (string)listView.ItemContainerGenerator.ItemFromContainer(listViewItem);
         int index = listView.Items.IndexOf(nameToReplace);

         if (index >= 0)
         {
            listView.Items.Remove(name);
            listView.Items.Insert(index, name);
         }
     }
     else
     {
        listView.Items.Remove(name);
        listView.Items.Add(name);
     }
   }
}

What brings all this code together is the BeginDrag method which is really the heart of the operation. Here it creates an adorner and handlers to update the adorner so that it shows the item actually being dragged. It also makes the vital call to DragDrop.DoDragDrop which actually fires off the drag/drop operation.

        private void BeginDrag(MouseEventArgs e)
        {
            ListView listView = this.listView;
            ListViewItem listViewItem =
                FindAnchestor((DependencyObject)e.OriginalSource);

            if (listViewItem == null)
                return;

            // get the data for the ListViewItem
            string name = (string)listView.ItemContainerGenerator.ItemFromContainer(listViewItem);

            //setup the drag adorner.
            InitialiseAdorner(listViewItem);

            //add handles to update the adorner.
            listView.PreviewDragOver += ListViewDragOver;
            listView.DragLeave += ListViewDragLeave;
            listView.DragEnter += ListViewDragEnter;

            DataObject data = new DataObject("myFormat", name);
            DragDropEffects de = DragDrop.DoDragDrop(this.listView, data, DragDropEffects.Move);

            //cleanup
            listView.PreviewDragOver -= ListViewDragOver;
            listView.DragLeave -= ListViewDragLeave;
            listView.DragEnter -= ListViewDragEnter;

            if (_adorner != null)
            {
                AdornerLayer.GetAdornerLayer(listView).Remove(_adorner);
                _adorner = null;
            }
        }

Part Two

This part will show how to get the visual drag, I use the visual brush of the listViewItem to get the item to drag and change its opacity so that it has a ghosted appearance. You need to create a DragAdorner object and derive it from the adorner class. Download the sample to see how it is implemented. Before the drag/drop operation is fired off I create the adorner, and add Drag event handlers to ensure the adorner is updated to the mouse location. See below for code extract.

        private void InitialiseAdorner(ListViewItem listViewItem)
        {
            VisualBrush brush = new VisualBrush(listViewItem);
            _adorner = new DragAdorner((UIElement)listViewItem, listViewItem.RenderSize, brush );
            _adorner.Opacity = 0.5;
            _layer = AdornerLayer.GetAdornerLayer(listView as Visual);
            _layer.Add(_adorner);
        }

        private void ListViewQueryContinueDrag(object sender, QueryContinueDragEventArgs e)
        {
            if (this._dragIsOutOfScope)
            {
                e.Action = DragAction.Cancel;
                e.Handled = true;
            }
        }

        private void ListViewDragLeave(object sender, DragEventArgs e)
        {
            if (e.OriginalSource == listView)
            {
                Point point = e.GetPosition(listView);
                Rect rect = VisualTreeHelper.GetContentBounds(listView);

                //Check if within range of list view.
                if (!rect.Contains(point))
                {
                    this._dragIsOutOfScope = true;
                    e.Handled = true;
                }
            }
        }

        void ListViewDragOver(object sender, DragEventArgs args)
        {
            if (_adorner != null)
            {
                _adorner.OffsetLeft = args.GetPosition(listView).X;
                _adorner.OffsetTop = args.GetPosition(listView).Y - _startPoint.Y;
            }
        }

To get a full idea of how the code works download the code and see it in action.
click here to download