Inter-Column communication in a WPF GridView

Loads of times I have been asked in forums, how do I make a GridViewColumn communicate with another in WPF. A common use case is that you have a checkbox in Column1 and you want that when the checkbox is checked something happens in Columnx.

The first obvious answer is make a property in your business object that can reflect that change. Yet some times this is strictly UI and you don’t want to clutter your business object with UI code.

One solution could be to use the power of DataBinding. Lets start by explaining in very high level, how a GridView works. So a GridView is simply a Logical entity. To make it sound more familiar we can say that a GridViewColumn is like Grid ColumnDefinition / RowDefinition. It’s an entity that will effect how the parent (in our case the ListView) will look. A GridView will construct a GridViewHeaderRowPresenter and a GridViewRowPresenter that will construct the header of the ListView and the ListView rows. Because the GridView does this, we can do a trick with databinding that will enable us to make Inter-Column communication possible.

Basically the idea is to bind the CheckBox’s IsChecked property to the Tag property of it’s GridViewRowPresenter with a OneWayToSource binding. This will make sure that when the user check/unchecks the Checkbox the IsChecked state is stored in the GridViewRowPresenter. something like this

   1: <GridViewColumn Header="checkbox here" Width="100">
   2:     <GridViewColumn.CellTemplate>
   3:         <DataTemplate>
   4:             <CheckBox IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type GridViewRowPresenter}}, Path=Tag, Mode=OneWayToSource}"/>
   5:         </DataTemplate>
   6:     </GridViewColumn.CellTemplate>
   7: </GridViewColumn>

Now that we have that in place other columns can easily become aware of the state changes by doing a DataTrigger on the GridViewRowPresenter like so

   1: <GridViewColumn Header="text here" Width="100">
   2:     <GridViewColumn.CellTemplate>
   3:         <DataTemplate>
   4:             <TextBlock Text="{Binding}" Foreground="Red" x:Name="text"/>
   5:             <DataTemplate.Triggers>
   6:                 <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type GridViewRowPresenter}}, Path=Tag}" Value="True">
   7:                     <Setter TargetName="text" Property="Foreground" Value="Green"/>
   8:                 </DataTrigger>
   9:             </DataTemplate.Triggers>
  10:         </DataTemplate>
  11:     </GridViewColumn.CellTemplate>
  12: </GridViewColumn>

 

and that’s basically it…

 

Thank you WPF!!!! We love you 😀

Download demo Application

AvalonControlsLibrary DatePicker refactored

Recently I received some requests from people to support some more styling for the DatePicker control. The initial idea for the DatePicker was to create a “lookless” control and then users would create a ControlTemplate to change the look and feel of the control (which is still 100% possible, see here for more info). Yet sometimes users do not want to totally change the look of the control, sometimes it’s more a matter of changing colors and minor things like that. So I decided to make the DatePicker support some more styling so that users don’t need to create a new ControlTemplate for the DatePicker if they only need to change minor things in the DatePicker UI.

As you can see in the image above I added 5 new properties for styling the control. All of these properties are optional and if they are not set, a default value will be set for you.

DayCellTemplate

This property accepts a DataTemplate where the user can specify how each Day cell should look. The DataTemplate is fed with a DayCell object as DataContext. The DayCell class has the following properties which you can use in the DataTemplate

Property Name Type Description
DayNumber int Represents the Day number
MonthNumber int Represents the Month number
YearNumber int Represents the Year number
IsEnabled bool Flag that indicates if the item falls out of the MinDate and MaxDate range
IsInCurrentMonth bool Flag that indicates if the item is in the current selected month

Here is a sample DataTemplate for the DayCellTemplate.

<DataTemplate>
    <Border Name="border">
        <TextBlock Text="{Binding DayNumber}" Name="dayCell"/>
    </Border>
    <DataTemplate.Triggers>
        <!--This trigger is to do some thing with the template when an item is selected-->
        <DataTrigger Binding="{Binding RelativeSource={
                                RelativeSource AncestorType={x:Type ListBoxItem}},
                                Path=IsSelected}"
                     Value="True">
            <Setter Property="Background" Value="Blue" TargetName="border"/>
        </DataTrigger>
        <!--This is for those dates that fall out of the MinDate and MaxDate.-->
        <DataTrigger Binding="{Binding IsEnabled}" Value="False">
            <Setter Property="Background" Value="Gray" TargetName="border"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding IsInCurrentMonth}" Value="False">
            <Setter Property="Foreground" Value="Gray" TargetName="dayCell"/>
        </DataTrigger>
    </DataTemplate.Triggers>
</DataTemplate>

So basically the DayCellTemplate will give you a lot of flexibility in terms of what you can do with the UI of the DatePicker because you can make the Day cell look however you want without the need of re building the whole UI for the control.

DayHeaderTemplate

The DayHeaderTemplate is again another DataTemplate, this time it will be a DataTemplate for the Header Day cell which basically is the Text -> Sun, Mon, Tue etc.. The DataTemplate that you set as being the DayHeaderTemplate will be passed a string object as DataContext that contains the Text for the Header (ex. Mon, Tue etc..) Here is an example of a DataTemplate that can be applied for the DayHeaderTemplate property.

<DataTemplate>
    <Border Background="Yellow">
        <TextBlock Foreground="Lime" Text="{Binding}"/>
    </Border>
</DataTemplate>

MonthBackButtonStyle/MonthForwardButtonStyle

These two properties are the styles for the back and forward month navigation buttons of the DatePicker. Basically you can apply a style for the Back and Forward button in any way you like. So you may decide even to create a ControlTemplate for these two buttons which would be quite easy. Something like this….

<Style TargetType="Button">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border BorderBrush="Pink" Width="20" BorderThickness="2">
                    <TextBlock Text="<" FontWeight="Bold"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

MonthSelectorStyle

Last but not least is the MonthSelectorStyle property. This property enables you to set a style for the Months drop down list aka ComboBox. Since here we are setting a scyle for a ComboBox a user has full control over that combobox. One can decide to do a ControlTemplate for the ComboBox or maybe just set an ItemTemplate for the elements inside it… Here is a style that I used in the demo app of the DatePicker…

<Style TargetType="ComboBox">
    <Setter Property="Background" Value="Yellow"/>
    <Setter Property="ItemContainerStyle">
        <Setter.Value>
            <Style TargetType="ComboBoxItem">
                <Setter Property="Background" Value="Yellow"/>
            </Style>
        </Setter.Value>
    </Setter>
    <Setter Property="ItemTemplate">
        <Setter.Value>
            <DataTemplate>
                <TextBlock Foreground="Red" Text="{Binding}"/>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

Conclusion

I think that with the introduction of these properties the DatePicker control will be much more easy to use and re style. Again I would suggest that if you need to totally re arrange the look of this control the best way would be to use a ControlTemplate and change the whole look of the control, yet if all you need is to change some colors and other minor things, these new properties will help you out in the process.

The new version of the DatePicker will be available in the AvalonControlsLibrary v3, yet I know you can’t wait until you get your hands on this so I created a demo app for you 😀

I am open to suggestions as usual! Please let me know if there is something missing or something that you would like to have in YOUR AvalonControlsLibarary DatePicker 🙂

And as my friend Sacha Barber says – “It’s all good!” 😀

Download Demo Project

kick it on DotNetKicks.com

Creating a File Explorer in WPF using MVC+M

Introduction

In my previous article I explained how one can use the Mediator Pattern together with the MVC Pattern to structure the code in a very neat way. If you did not read my previous article I would suggest that you do, since I am basing this post on the assumption that readers already read that post.

I am writing this post because some friends from WPF Disciple suggested that I use a better example for the MVC+M. I agree 100% with them since the example that I did in my previous post was not the best one I could pick up…

Today I’ve got a new problem that I want to solve using the MVC+M. As the title of the post suggest, we are going to build a File Explorer and hopefully it will look something like this.

Yea, that’s where AvalonControlsLibrary and all other projects of mine live 😀

This application is very simple to explain because I would assume that everyone reading this post has used a File Explorer. Basically we have a TreeView that shows the directories and when a directory is selected the list of files in that directory show up on screen.

The Problem

The problem is that we do not have a fixed list of objects. The list is generated on the fly. If we had to load all directories in memory we would have a big performance hit + I don’t want to imagine the memory consumption. So for the TreeView I used the Flyweight Design Pattern. I will not go into details of this pattern since it is not the purpose of this post, but to summarize, each node loads a dummy child so that the user can expand the items. Once an item is expanded the TreeView controller loads the child directories of the directory being expanded.

You’ll say “OK… But what does this have to do with the Mediator?”. The Mediator comes in handy for our second problem. When an item is Selected the list of files show up in the file list (on the right hand side of our application).

So the problem here is, we have a Dynamic Hierarchal List + we have a Treeview (which does not have an IsSynchronizedWithCurrentItem property that can make the underlying ICollectionView notify us with the currently selected item). Speaking of which we now don’t even have one ICollectionView, instead we have one for each level.

How can we tell the File List Controller that an item is selected without coupling it with the Tree View Controller?

The Solution (or at least, how I would do this…)

In such a case the Mediator is key, because the mediator will make the communication between the 2 controller very easy and loosely coupled. Let me first introduce the entities we have here

Views

– DirectorySelectorView

– FileSelectorView

Controllers

– DirectorySelectorController (mentioned above as TreeView contoller)

– FileSelectorController (mentioned above as File List Controller)

Model

– FileSystemDataService

OK so lets’ do this… And guess what we are going to do this in 3 steps once again.

Step 1 – Publish the Directory Selected message via the Mediator
Step 2 – Register the FileSelectorController to receive a notification for the Directory Selected message.
Step 3 – Handle the Directory Selected message in the FileSelectorController and get the files to display.

Lets now talk in C#. The following is the code to do the above mentioned 3 steps.

Step 1

//event handler for the selecting changed
void ItemSelected(object sender, RoutedEventArgs e)
{
    TreeView treeView = (TreeView)e.OriginalSource;
    //Send a message that an item is selected and pass the object selected
    Mediator.NotifyColleagues(
        Messages.DirectorySelectedChanged, treeView.SelectedItem);
}

Step 2

public FileSelectorController()
{
    Mediator.Register(this, new[]
    {
        Messages.DirectorySelectedChanged
    });
}

Step 3

public override void MessageNotification(string message, object args)
{
    switch (message)
    {
        case Messages.DirectorySelectedChanged:
            //load all files for the directory specified
            LoadFiles((DirectoryDisplayItem)args);
            break;
    }
}

That’s all folks …. Download the full source code to see all the rest…

Some Side notes to keep in mind

Developers are like artists. Everyone has his own style. For example, right now the Mediator implementation that I did, is using an interface driven design where you have an interface IColleague and the mediator notifies the colleagues passing the message that is being sent. One can implement a Mediator that uses strongly typed delegate so that you can avoid doing the switch statement (in the MessageNotification method) and implementing the IColleague interface for each controller. So the implementation of such a Mediator would look like this

Register( IDictionary<string, Action> callbacks);

The Colleague that want to register simple do the following

Register( new Dictionary<string, Action>
{
     { Messages.SelectionChanged, delegate(object obj){ //DoSomething here  } }
}

This would totally eliminate the switch statement and the ICollegue interface…

One thing that I have been discussing with some friend from WPF Disciples is, What about big systems? Would big systems have to define loads of Messages?

The answer (at least how I see it from previous experiences working with this pattern) is NO. Why? Because the messages would be only for the controllers part. The other parts of the system would not need such a thing because if the controllers can talk together, the other entities would not need to. If we take the example of the File Explorer, the Views do not need to communicate because the controllers are synchronizing with each other. The views are just reading the data from the controllers. The model does not need this system either because the model will just give data that is being requested from the controller. So, please do not misinterpret this and use this system all around because you would create a MONSTER!

Josh Smith, also pointed out a very good point. What about memory leaks? If controllers do not unregister from the mediator once that the contoller is disposed than the controller would still exist in memory. This is a fact! I did not implement an unregister in the mediator because till now I only had controllers that do not get disposed throughout the application life cycle. Yet to implement an unregister would be just a piece of cake. All you have to do is to ask the mediator to remove the reference to a specific controller when the contoller is being disposed.

Besides the Mediator, there are loads of other ways of doing this, yet I decided to stick to this one because currently I feel that this pattern is given me the flexibility I need.

Conclusion

I like how this works because I feel that I can have a loosely coupled and high cohesion code base.

Loosely coupled, because the controllers know nothing about each other and I can just disable or reuse one of them at any point in time.
High cohesion, because knowing that I can make controllers communicate in an easy way, I create controllers that have one responsibility.

Credits

Thanks to all WPF Disciples for the brilliant discussion
My friend Karl Agius for even some more discussions

Download the full source code of the Demo application.

kick it on DotNetKicks.com

More than Just MVC for WPF

Introduction

First of all I am assuming that the readers already know how to use the MVC design pattern for WPF (or at least read about it and understand the concept). If not I would suggest that you read this brilliant post by Josh Smith. I am writing this article because recently I found a problem when using the MVC in WPF and I think I found a neat solution. Well I said that “I” found the solution, that is not true. The pattern that I am going to talk about is called the Mediator Pattern and I found it in the Gang of Four book that I was reading recently. I decided to mix the 2 patterns together and the result was beautiful code.

Warning: This article is a bit long. Readers can fall fast asleep 😀

Problem Definition

The way I see it, Views must be as small as possible and handle only one specific job. Let’s do a practical example. Let’s say we have an application that displays a list of products. The application also lets you click on a specific product and the details of that product would show on the side. A search feature is also provided in this application. So our application would look something like this (I coloured the different sections of the app to make them more obvious)

Let me introduce the Entities that we have here

Controllers (These are simple class nothing more)

– ProductListController

– ProductDetailsController

– SearchController

Views (These are all User Controls)

– ProductListView

– ProductDetailsView

– SearchView

All views create an instance of the related Controller and set the Controller instance as the DataContext. By doing this the View can data bind to the properties of the Controller and also the Controller can handle routed command and routed events from the View since the Controller is now in the WPF logical tree. In this way the View has 0 lines(excluding the InitializeComponents) of code in the code behind file and all logic is inside the Controller class. By doing this you can easily Unit Test the logic and also Designers can use tools such as Expression Blend without having any problem because the logic is handled in the controller class and not in the view itself. Just like MVC in Web so to speak. Imagine commands in WPF as being the Routed URL for the controller to handle.

One may say “Wow, that’s a lot of classes” but hey if you want to be flexible, scalable and have code reusability that is the way to go. If not, then go ahead and put everything in one class but the result will be strongly coupled entities that are not reusable. Sometimes this is perfectly acceptable and so YES go ahead and do that. But let’s say you need to do a Search feature in another page. With MVC you can just re-use the search view and search controller in the other page.

In the MVC for WPF (or better in one of the implementations), there is a strong use of Routed Commands (sometimes one may use also Routed Events, well at the end of the day a RoutedCommand is just a Routed Event + the Command Pattern nothing more). The problem with Routing Commands is that the communication is always done from child to parent in the logical tree. In the application above there is a need of something different. Basically the Controllers need a way how to communicate. Yet we do not want that the Controllers know about each other because if that was so why not create 1 View and 1 Controller. We must ensure that no coupling is made between the controllers.

In the sample application above the ProductListController is handling the SelectionChanged event of the ProductListView. ProductListController needs to communicate this to the ProductDetailsController so that it updates the data that is currently being shown in the ProductDetailsView.

The question is how can you achieve this?

The Mediator Pattern to the rescue

The Mediator pattern can be described as a ChatRoom. In a Chat room there are Colleagues (the persons in the Chat Room) and via the Mediator (the chat room itself) they exchange messages. The same can be applied for our Controllers. There would be 1 Mediator and all Controllers communicate to each other via the Mediator. In simple english the Colleagues would be the Controllers.

The following is the Class Diagram for the application I mentioned above

The interface for the Mediator would look something like this

The signature of the methods would look like this

/// <summary>
/// Registers a Colleague to a specific message
/// </summary>
/// <param name="colleague">The colleague to register</param>
/// <param name="messages">The message to register to</param>
void Register(IColleague colleague, IEnumerable<string> messages);

/// <summary>
/// Notify all colleagues that are registered to the specific message
/// </summary>
/// <param name="message">The message for the notify by</param>
/// <param name="args">The arguments for the message</param>
void NotifyColleagues(string message, object args);

The IColleague interface is an interface that all Controllers implement and looks like this

The Signature for the MessageNotification would look like this

/// <summary>
/// Notification from the Mediator
/// </summary>
/// <param name="message">The message type</param>
/// <param name="args">Arguments for the message</param>
void MessageNotification(string message, object args);

Aha…. but Marlon how does this solve the Problem ??!!??

With the Mediator pattern Controllers can send messages to each other without knowing of each other. Let’s do an example to try and make this more clear. Lets use the problem that I described above.

ProductListController is handling the SelectionChanged event of the ProductListView. ProductListController needs to communicate this to the ProductDetailsController so that it updates the Data that is currently being shown in the ProductDetailsView”

All we need to do is 3 things

1.0 ProductDetailsController registers to the SelectProduct message (the message is just a constant string defined in a common class named Messages)

1.1 ProductDetailsController updated the Selected Product when this message is sent.

2.0 ProductListController sends a message via the Mediator that a new product has been selected

Code for 1.0

public ProductDetailsController()
{
    //register to the mediator for the SelectProduct message
    Mediator.Register(this, new string[]
    {
        Messages.SelectProduct
    });
}

Code for 1.1

/// <summary>
/// Notification from the Mediator
/// </summary>
/// <param name="message">The message type</param>
/// <param name="args">Arguments for the message</param>
public override void MessageNotification(string message, object args)
{
    switch (message)
    {
        //change the CurrentProduct to be the newly selected product
        case Messages.SelectProduct:
            CurrentProduct = (Product)args;
            break;
    }
}

This will set the CurrentProduct property of the ProductDetailsController to be the new product that has been selected (the product object has been sent via the Code in 2.0). The CurrentProduct property of the ProductDetailsController is being data bound in the view. When the CurrentProduct is set the property raises a PropertyChanged notification, so that the binding is updated with the new value.

Code for 2.0

//event handler for the selection changed
void SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    //Notify that the selected item has changed
    if(e.AddedItems != null && e.AddedItems.Count > 0)
        Mediator.NotifyColleagues(Messages.SelectProduct, e.AddedItems[0]);
}

And this is what I call the MVC + M

hehe… Funny name but for me this is doing miracles. I am currently using this in one of my projects at work and I can confirm that this absolutely works. One may say but this application could have been done with other thing that WPF offers, and I agree 100%. The example application that I used in this post can be easily implemented by putting the list of data in the Model and binding to it (like in MVVM). For the selection part, you can use the Current item of the ICollectionView and everything would work. Yet when you need to do more than just “Select item and data changes somewhere else” than the MVC + M comes useful.

Conclusion

MVC + M is a neat mix of the MVC pattern with the Mediator pattern. The MVC makes things much easier to test and much more isolated and controlled. The Mediator makes communication between Controllers possible in a loosely coupled manner. For me this works really well and I hope that it will do the same for your applications. Download the source code to have a look at my humble implementation.

Any comments, questions and suggestions are as usual most welcome…

P.S I am sorry if this post was a bit long but I didn’t manage to make it any shorter.

See also Part 2

Download the Source code of the Sample Application

kick it on DotNetKicks.com

WPF Treeview root node

Unfortunately the WPF native treeview or treeview items do not expose a property to determine which item is the root node in the treeview. I needed such a feature and thought to put it on my blog…

What is a treeview?
Well believe it or not a TreeView is just an Items Control nothing more. Yes, an ItemsControl that creates TreeViewItems as it’s Item Containers. The TreeViewItems are also ItemsControl so a recursive data structure is formed and the TreeViewItems generate there own child nodes.

Today I will not go into details of how the treeview and ItemsControl work… For more info on this visit Dr.Wpf Blog. I will discuss more how I implemented the root nodes for the treeview.

So an ItemsControl has a very special method that one can override to do some custom logic, “PrepareContainerForItemOverride“. The following is the signature of the method

protected override void PrepareContainerForItemOverride(
    DependencyObject element, object item)

Basically this method gets called whenever an item (in our case a TreeViewItem) is being created and decorated with a DataTemplate (if set). In this method we can set a property of the TreeViewItem to identify the item as a root node.Ok, lets start. First we need to sub class the Treeview control. Once we did that we need a way how to attach information to the TreeViewItems… HMMM.. what better could do this then Attached Properties. Once we have all this, we need to set the attached property to True for the root nodes and we are done 🙂 …. something like this

public class MyTreeView : TreeView
    {

        public static bool GetIsRootNode(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsRootNodeProperty);
        }

        public static void SetIsRootNode(DependencyObject obj, bool value)
        {
            obj.SetValue(IsRootNodeProperty, value);
        }

        public static readonly DependencyProperty IsRootNodeProperty =
            DependencyProperty.RegisterAttached("IsRootNode", typeof(bool),
            typeof(MyTreeView), new UIPropertyMetadata(false));

        protected override void PrepareContainerForItemOverride(
            DependencyObject element, object item)
        {
            SetIsRootNode(element, true);
            base.PrepareContainerForItemOverride(element, item);
        }
    }

So the most important part is where we set the Attached property IsRootNode to true (Please also note that by default the Attached property is set to false). You would be wondering, But wouldn’t this make all TreeViewItems root nodes???!!??? And the answer is, NO. Because the Treeview only generate root nodes. all other nodes are generated by the TreeViewItems themselves (Remember that the TreeViewItems are ItemsControl as well :)).

Once we have the property IsRootNode set we can restyle the TreeView as we want by using a Control Template. something like this

<ControlTemplate TargetType="TreeViewItem">
    <StackPanel Margin="10,2,0,0">
        <WrapPanel Name="item">
            <ToggleButton Name="expander"
                          IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, 
                                              Path=IsExpanded}"
                          Content="+"/>
            <ContentPresenter x:Name="PART_Header"
                  ContentSource="Header" />
        </WrapPanel>
        <Border>
            <ItemsPresenter Name="children" Visibility="Collapsed" />
        </Border>
    </StackPanel>
    <ControlTemplate.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter TargetName="item" Property="Background"
                    Value="LightBlue"/>
        </Trigger>
        <Trigger Property="IsExpanded" Value="True">
            <Setter TargetName="children" Property="Visibility"
                    Value="Visible"/>
        </Trigger>
        <Trigger Property="HasItems" Value="False">
            <Setter TargetName="expander" Property="Visibility"
                    Value="Collapsed"/>
        </Trigger>
        <Trigger Property="local:MyTreeView.IsRootNode" Value="True">
            <Setter TargetName="item" Property="Background" Value="Silver"/>
            <Setter TargetName="item" Property="Height"  Value="50"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

The most important part of this ControlTemplate is the Trigger on the attached property local:MyTreeView.IsRootNode.Here we are making the RootNodes for the treeview look different from all other nodes…

Hope this post helps…. Please contact me if you need any help 🙂

Download the full source code

Input Prompt support in WPF

Intro

If you look at Vista User experience guide, one thing that is a must have is the Input Prompt. I think that this is very important to improve the user experience. Yet unfortunately this is not supported natively by WPF 😦

But don’t worry because AvalonControlsLibrary is at the rescue 🙂

I had noting to do today so I decided to create this functionality and share it with you guys… You would say, aha; here comes Marlon with a new control. But NO. This is not a control as such. What I have created is a class with some attached properties that can be used to have the Prompt Input feature for any control (or better any control that would make sense such a feature). I choose the attached properties approach rather than creating a custom control for the simple reason to support any control that you wish to have an input prompt like the one displayed in the image below.

Input prompt

As you can see in the image above I am using the Input Prompt both for the TextBox and the ComboBox. And yes you can use it with any control that you want…

How to use this…

Well using this feature is quite easy, all you have to do is to set an attached property in your control. Something like this…

<TextBox local:InputPrompt.PromptText="Enter Search" />

[where local is the XAML namespace mapping]

In total there are 8 properties that you can set which are

  1. InputPrompt.PromptText – I guess you already figured this one out 😀
  2. InputPrompt.PromptColor – This is a brush used as foreground for the Prompt Text (Default: Gray)
  3. InputPrompt.PromptFontFamily – The font family to use for the Prompt Text (Default: Arial)
  4. InputPrompt.PromptFontSize – The font size of the Prompt Text (Default: 12.0)
  5. InputPrompt.PromptFontStretch – The font stretch to use for the Prompt Text (Default: FontStretches.Normal)
  6. InputPrompt.PromptFontStyle – The font style to use for the Prompt Text (Default: FontStyles.Normal)
  7. InputPrompt.PromptFontWeight – The font weight to use for the Prompt Text (Default: FontWeights.Normal)
  8. InputPrompt.PromptBackColor – This is a brush that is used to color the background of the prompt (Default: Transparent)

Please note: You must set the InputPrompt.PromptText in order for this to work all the other properties are optional. Also you must have you control under an AdornerDecorator because the InputPrompt will draw the prompt text in an adorner.

If you use the Input Prompt with a textbox the input prompt will be much more intelligent. What do I mean by this? Basically the Input Prompt handles the Text Changed event of the TextBox and if the user enters no text the prompt re appears. The same happens if the TextBox looses focus and there is no text in it. I did this behaviour for the TextBox because this is the standard behaviour for an Input Prompt for textboxes.

How does this work behind the scenes

Well it’s quite simple. Basically an Adorner is placed on top of the control which sets the Attached properties and draws the InputPrompt.PromptText. Besides drawing the text this also draws a rectangle covering the surface of the control so that as soon as the user click the control(or better mouse down on the control), the adorner disappears and the control gets activated once again.

When the InputPrompt.PromptText is set for a TextBox, the input prompt will register to the LostFocus event and the TextChanged event and make sure to display the Prompt Text if the Text of the TextBox is to empty.

Conclusion

All this will be included in AvalonControlsLibrary v3 but I decided to upload a demo as a stand alone so that you can start using this immediately.

Hope you like this and as usual I am all ears for feedback and suggestions….

Thanks

Download Source Code and Demo App

kick it on DotNetKicks.com

Support for MinDate and MaxDate in DatePicker and TimePicker

I updated the sources for AvalonControlsLibrary v2 so that to support MinDate and MaxDate in the DatePicker.

Also added support for MinTime and MaxTime in TimePicker.

And while I was at it I also refactored the DateTimePicker to support these 2 properties.

The properties are DependencyProperties so you can easily databind to and do what every you like with them….

Great… now i should go to sleep 😀

Downlaod the new version

AvalonControlsLibrary v2 has been released !

Finally I had some time to release the new version of AvalonControlsLibrary v2.

This release includes

RangeSlider – All properties are now Dependency properties so that you can easily databind with.
RangeSlider – The RangeSelectedChanged event has been refactored into a Routed event.
Range slider – Support for Commands such as MoveBack Move Forward, AllBack and AllForward

DatePicker – Add a DateSelectedChanged routed event – TimePicker – Add a TimeSelectedChanged routed event

DateTimePicker (this will be the DatePicker and TimePicker joined)

DockableContainer (aka Docky- This is a brand new control which supports docking of element and undocking. While elements are un docked you can drag around the element 🙂 Just like Blend Toolbars)

Bug Fixes
Masked TextBox IsReadonly click here for more info
DateTimePicker – setting the date via code before the ControlTemplate being loaded was thowing an exception

Download the new version

Send as much feedback as you can so that I can start working on V3 😀

Thanks for all your support

kick it on DotNetKicks.com

GridViewColumn DisplayMemberBinding vs CellTemplate

GridViewColumn has 2 different ways how one can specify the content of a cell. One can use the DisplayMemberBinding or also a CellTemplate. DisplayMemberBinding is used when you just want to show some text inside your GridViewColumn. You can use this property as follows

<ListView>
    <ListView.View>
         <GridView>
             <GridViewColumn DisplayMemberBinding="{Binding Name}"
                                    Header="Name"/>
         </GridView>
    </ListView.View>
</ListView>

So basically all you have to do is specify a binding to the property of the object being bound. In reality the DisplayMemberBinding will create a TextBlock and bind the Text property of the TextBlock to the binding that you specify. Yet if you need more than just text in a TextBlock then DisplayMemberBinding is not what you should be looking for. For such scenario one should use the CellTemplate.

The CellTemplate property of the GridViewColumn allows you to enter a DataTemplate where you can put in whatever you like as controls to be rendered by the GridView. Let me give you an example of how one can use the CellTemplate to do something more than Text

<ListView>
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Image">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <Image Source="{Binding Image}"/>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

So in the above example the ListView is now rendering an image where the source of the image is set via a binding to a property of the object being bound to. This gives you much more flexibility in terms of what you can do inside a Cell. For even more advanced scenarios where you have to decide how to render the cell according to the object being bound you can also use the CellTemplateSelector.

Final and most important point about these 2 properties…
DO NOT USE THEM TOGETHER!

If you set the DisplayMemberBinding it is useless to set the CellTemplate because the GridView will only use the DisplayMemberBinding and ignore the CellTemplate. So always make sure that you only set one of these properties and not both at the same time otherwise you will not get the results that you were hoping for.

Want to read some more on ListView? Click here