In order to customize controls the way you want, you can either use a DataTemplate, different specific ControlTemplate properties, use the properties that the controls publish, but in the end, to get it right, you must actually change the ControlTemplate of the control itself. The best practice is to use an external resource dictionary that contains a style that changes various properties and also, if needed, the ControlTemplate.

The problem there is that there is no way to partially change the control template. I mean, yeah, I could think of a few ways, but in the end is the same thing: you need to replace the control template completely. And now you have two ... err.. actually three problems.

First, there are ways of getting the default control template, with all the functionality (we are talking about one, two or even more pages of XAML) and change only what you want. It's not trivial, but it can be done, either by copying it from the published sources (like the Windows SDK or the Expression Blend SystemThemes folder) or by using a utility like ShowMeTheTemplate.

Second, there is the issue of control templates differing depending on the Windows theme. And therefore one must either accept that the application will only look one way for every theme and Windows operating system, or provide templates for all the themes available (there are 6 defaults and a generic fallback theme).

Now, there are many tutorials about how to do that, basically just create a Themes folder, change AssemblyInfo.cs to

[assembly: ThemeInfo(
ResourceDictionaryLocation.SourceAssembly, //where theme specific resource dictionaries are located
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
)]

, copy the xaml files (with certain names) there and change them as you see fit. There is a catch, though! This will only work on your custom controls. Default controls already have a template in the operating system theme, so you need to do one extra thing in order to overwrite them, and that is to write the following in the a parent control Resources block:

<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="{ThemeDictionary [LibraryOrApplicationNamespace]}" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

otherwise it will NOT work.

You can get the same result by adding this to the static constructor of the control, provided you have access to the sources:

DefaultStyleKeyProperty.OverrideMetadata(typeof([MyControlClass]), new FrameworkPropertyMetadata(typeof(MyControlClass)));


One thing you also need to be aware of is that Visual Studio caches the themes. If you change them, especially if you do it outside visual Studio, you need to force a Rebuild of the project.

I've decided to write this entry before I could actually master these tools because I don't think I will afterwards (I'd be too old to type). So here it goes:

  1. ReSharper - yes! I will probably need a ReSharper blog tag. This thing is good for everything! Its XAML smart intellisense is a gem, as well as the various options you get when writing WPF code or XAML
  2. Snoop - this is a very small tool that acts like a WPF FireBug. It can select an element, show properties, even change some of them
  3. Mole Visualizer - this is a Visual Studio debug visualizer, one that allows very detailed exploration of debugged objects, especially WPF elements
  4. XAML Power Tools - a Visual Studio addon, it allows a lot of stuff, like automatically generate the view from a model, extracting a style from a control, etc
  5. KaXaml - a tool that works like a XamlPad, but has more options. You basically use it as a poor man's Blend; and it's very light
  6. XamlPad - this is a Microsoft tool. Unfortunately, to use it you need to download the entire Windows SDK for Windows Server 2008 and .NET Framework 3.5, which is 1.5Gb in size
  7. Pistachio - this is a Visual Studio project resource browser. Give it the project and you can see the brushes, the style, the templates, the usages
  8. Expression Blend - the de facto Microsoft tool for editing XAML and working with design stuff. Not only it is not free, but it is also buggy. Unfortunately, I have a hunch I will have to use it in the near future to work with WPF styles
  9. ShowMeTheTemplate - Small application that explores the WPF default templates for various controls



All of the tools above, except ReSharper and Blend are free to use.

So I wasted 15 minutes on trying to make a converter work within a TemplateBinding. Even if there is no error returned, the converter is never called. Funny, no?

I was trying to bind a property to the value of a property of the parent UserControl in WPF. When you google for it you get something pretty interesting: give a name to the user control right inside the user control XAML, then reference it with ElementName.

What I found after hours of torment was that this doesn't always work. I guess it only works up to the first item container in the logical tree and then stops. So that when I tried to use a property ImageSource of the user control in a Menu.Icon it failed!

My solution looks pretty ugly, but it does work in all cases!


<Image Source="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type Controls:MyUserControl}},Path=MainMenuImageSource}"
Width="16" Height="16"></Image>



In other words: find the ancestor of the type of your user control and use it as the RelativeSource of the binding.

Update: When I had more time to thing I realised that a MultiBinding needs a Converter, but a simple Binding also has a Converter and I guess that is what I should have used. I will update the post when I get to work on Monday.

I started to build the prototype of a control and I hit a wall where WPF binding was concerned.

For example: I wanted to bind my control to a collection of Items which could be Groups, Sections or Items. Groups have more Sections and Items. Sections have more Items, but they should be displayed as a non clickable section with its Item children under it. Everything in a menu.

At first I used an XML data source, which allowed me to use XPath to select all the Items in a Group, all the Sections and all the Items in the Section like this: XPath="Item|Section|Section/Item". However, when switching to an object schema, the normal Path syntax was too restrictive to allow for this. Even with a MultiBinding, I could find no Path syntax in which to select children of a certain type and their children. However! MultiBinding uses a Converter to usually merge two or more collections together. I used it to get the children and their own children! So forget XAML in this case, just use code:

public class SectionHeaderConverter:IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
List<ToolBarItem> list = new List<ToolBarItem>();
foreach (IEnumerable<ToolBarItem> collection in values)
{
foreach (ToolBarItem element in collection)
{
list.Add(element);
var toolBarSectionHeader = element as ToolBarSectionHeader;
if (toolBarSectionHeader != null)
{
foreach (var item in toolBarSectionHeader.Items)
{
list.Add(item);
}
}
}
}
return list;
}

public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}


This converter was then used in the XAML as the Converter for the MultiBinding:

<MultiBinding Converter="{StaticResource SectionHeaderConverter}">
<Binding Path="Items"/>
</MultiBinding>


Now, that fixed one issue, but how can I now make the different MenuItems to
  1. have different looks depending on type/attributes
  2. behave differently depending on type/attributes
but selectively, keeping the default style and datatemplate in other cases? At first, when I used the XML datasource, having an XPath to select the type of the node based on its name was not an option because the XAML XPath implementation does not allow for XPath functions! so I used a StyleSelector for the difference between Sections (unclickable, spanning the whole width of the menu strip) and normal menu items, then a DataTemplateSelector for the difference between Groups and Items. It is also here where I bound the MenuItem Click RoutedEventHandler to an EventHandler in the datasource item class.


<Menu
ItemsSource="{Binding ElementName=ToolBarCurrent,Path=Items}"
ItemContainerStyleSelector="{StaticResource MenuItemContainerStyleSelector}"
ItemTemplateSelector="{StaticResource MenuItemTemplateStyleSelector}"
></Menu>


I don't know if that is the best way to do it, but suddenly it was like a fog lifted from my eyes and instead of that dreaded XAML I had something I know and understand used in a simple fashion. It is beyond the scope of this post to show how specific implementations of the selectors above work, but there are two issues that I had to fix:
  • Since the styles were resources defined in the resources of the containing Grid, I had to find a way to reference the Grid object from the StyleSelector:
    This is done using the
    ItemsControl ic = ItemsControl.ItemsControlFromItemContainer(container);
    var style = (Style) ic.FindResource("SectionStyle");
  • Since the data templates were resources defined in the resources of the containing Grid, I had to find a way to reference the Grid object from the DataTemplateSelector:
    this seems to be the same problem, but actually the solution was quite different, I used the FindVisualParent helper method like this:
    var ic = Helper.FindVisualParent<Grid>(container);
    The source for it is underneath.


public static TParentItem FindVisualParent<TParentItem>(DependencyObject obj)
where TParentItem : DependencyObject
{
DependencyObject current = obj;
while (current != null)
{
var tCurrent = current as TParentItem;
if (tCurrent != null)
return tCurrent;
current = VisualTreeHelper.GetParent(current);
}
return null;
}
.

Also, regarding this particular task, I found a way to display MenuItems grouped by a property in this blog post and at first I used this solution only to find out that this type of grouping only applies to flat DataTemplates. And while it seemed to be working in my first attempts with a HierarchicalDataTemplate, the grouping was only applied to the first level and not to the next.

My conclusion: as in many "magical" technologies, the complexity of a lot of problems is beyond the ability of the technology designers to predict. Therefore the only (and often enough, the best) option is to use your own code.

In Windows Presentation Foundation all resources (like ImageSources or Resource packs) are relative to the namespace of the control. So if you have a folder Images that holds your application icons and you use (in the application XAML) an ImageSource of "Images/MyImage.png" it will work. But as soon as the XAML is moved somewhere in a UserControl in the Controls namespace of a library, the ImageSource becomes invalid. It would only work as "../Images/MyImage.png" or "/Images/MyImage.png", even if the Controls namespace is not a folder and the control is in a library, not in the application that runs it!

This is part of a larger idea, that is Pack URIs. Pack URIs are used by the Open Packaging Conventions and are of the format pack://authority/path.


Long story short, authority can be application:/// or siteoforigin:///. The slashes at the end get escaped as commas in a pack URI so you get to have stuff like pack://application:,,,/ResourceFile.xaml. The path is more tricky: AssemblyShortName[;Version][;PublicKey];component/Path.
Attention at the component keyword. It is NOT a folder, but a keyword that must be there when referencing resources from an external library.

Example: I have the Resources/Images/image.png in a library and I want to use it in the XAML that is in the same library. The image source would be something like pack://application:,,,/libraryNameSpace;component/Resources/Images/image.png. Again look out for the component keyword.

Just yesterday I was struggling with the same issue, only this facette of it seems like a completely different bug. You see, I added this control to the library and everything worked fine EXCEPT the visual designer. It is known that the Visual Studio 2008 WPF designer is not the best possible piece of software, but this was one of those errors you don't know where it comes from.

So, let's take it from the beginning. I had something like
<HierarchicalDataTemplate DataType="{x:Type Code:League}" ItemsSource="{Binding Path=Divisions}">
<TextBlock Text="{Binding Path=Name}"/>
</HierarchicalDataTemplate>
Somewhere in the Window declaration there was a
xmlns:Code="clr-namespace:MyControls.Desktop.Code"
which is the namespace of the test application for the control in the library.
The application worked, but in the designer an error like "Type reference cannot find public type named 'League'.".

Many people gave the solution to remove the name of the assembly in the namespace declaration. So If I had something like "clr-namespace:MyControls.Desktop.Code;assembly=MyControls" and it was the current assembly, I should just remove it. Well, it wasn't the case here, was it?

In the end I found the solution here. You see, even if the assembly name was not specified, it was implied! And even if it was an application, not a library, it still was an assembly. And the Application name was... something with spaces in it!!

So, again, just go to the Project properties and change the Assembly name to not have spaces!

Two short points I'd like to make about working with WPF in Visual Studio 2008:
  1. In order to see Binding errors, you need to open the Output window while the app is running, since any binding error is silently dropped, but displayed there. There is also a Binding property called FallbackValue which you can set to "ERRRROOOORRR!!" :)
  2. XML files are seldom unformatted or having weird spaces and extra lines. Yet, there is not context menu for XML editors like the Format in ASP.Net as*x files. However, the option (and many more) is available in the Edit -> Advanced menu.
    • Format entire document: Ctrl+K, Ctrl+D
    • Format selection: Ctrl+K, Ctrl+F
  3. Unfortunately, some of the useful commands are just set up in the Options menu, like what to do with extra lines. So go to Tools -> Options -> Text Editor -> XAML -> Formatting.
    • To set it so that the XML is auto formatted at completion of start/end tag or when pasting code, go to the General option
    • To get rid of extra empty lines, go to the Spacing option and choose either Collapse multiple empty lines in content to a single line or Remove empty lines in content

It can't be done. Maybe in XAML 2009. In the old one, it just fails. I am using ReSharper and it automatically finds the controls in XAML in the loaded libraries and creates the appropriate namespace. For a library called "My Controls" it adds an "assembly=My Controls" at the end of the clr-namespace and the compilation fails with "Unknown build error".

The only solution I could find for this is to rename the library so that it doesn't have spaces in it. In my case the library was actually another project and I changed the name in the project properties to have underscore rather than space.

and has 0 comments
I have seen this used in a couple of places, the most prominent being LInQ. You run a method and then you chain another method to it and so on and so on. It's a nice improvement in readability and a good alternative to static methods.

The clearest example I can give you is on Wikipedia. Check it out. It's actually very easy to use and implement.

Tomorrow I start work on a WPF application that is supposed to be as modular as possible. Since I know almost nothing about WPF or modular applications, I started researching a little bit how it should be done. Basically I found only two ways I cared to expand my research on: Prism (patterns & practices Composite Application Guidance for WPF and Silverlight) and MEF (Managed Extensibility Framework).

Unfortunately I've only had time to do some Prism, although MEF seems to be the way to go. First of all it is a general framework, not limited to WPF/Silverlight and secondly it is used in the new Visual Studio 2010 release. What is amazing is that both frameworks come as freely available opensource.

Ok, back on Prism. The concepts are simple enough, although it takes a while to "get" the way to work with them. Basically you start with:
  • a Bootstrapper class - it initializes the Shell and the Catalog
  • a Shell - a visual frame where all the modules will be shown
  • a Module Catalog - a class that determines which modules will be loaded
  • an Inversion of Control Container - class that will determine, through Reflection usually, how to initialize the classes and what parameters they receive
  • a RegionManager - class that will connect views with Regions, empty placeholders where views are supposed to be shown
  • an EventAggregator - a class that is used to publish events or subscribe to events without referencing the objects that need to do that


Easy right? I don't even need to say more. But just in case you don't have a four digit IQ, better watch this four part video walkthrough:
Creating a modular application using Prism V2 - part 1
Creating a modular application using Prism V2 - part 2
Creating a modular application using Prism V2 - part 3
Creating a modular application using Prism V2 - part 4.

I did try to take the WPF Hands on Labs project and mold it with Prism and it partially worked. The problem I had was with the navigation controls. These work as a web application, where you call the XAML and it has to be a file somewhere, and you have events for the calling and returning from those "pages". I could find no way to encapsulate them so I could build no modules out of them and the whole thing collapsed.

So, for a quick walkthrough on using Prism with WPF.
Creating the core:
  1. create a new WPF application project
  2. reference the Prism libraries
  3. create the Bootstrapper class by inheriting UnityBottstrapper that will determine the Shell (a WPF window class) and set it as the application MainWindow, as well as create the type of ModuleCatalog (either take a default one or inherit one from IModuleCatalog) you want
  4. create the layout of the Shell and add region names to the controls you want to host the loaded modules (example <ContentControl Grid.Row="0" Margin="2" Regions:RegionManager.RegionName="SearchRegion"/>
.

Creating a module:
  1. create a new library project
  2. add a class that inherits IModule
  3. the constructor of the IModule can have different parameters, like an IRegionManager, an IUnityContainer, an IEventAggregator and any other types that have been registered in the container (I know it hasn't been initialized in the core, the catalog takes care of that). The IoC container will make sure the parameters are instantiated and passed to the module
  4. register views with regions and any additional types with the IoC container in the Initialize method of the module
  5. create view classes - WPF controls that have nothing except the graphical layout. Any value displayed, any command bound, any color and any style are bound to the default DataContext. The views will receive a view model class as a constructor parameter which they will set as their DataContext
  6. create the view model classes - they also can have any types in the contructor as long as they are registered with the IoC container, stuff like the eventAggregator or a data service or other class that provides the data in the view model.
  7. provide all the information needed in the view as public properties in the view model so that they can be bound
  8. subscribe or publish events with the event aggregator


As you can see, most of the work is done by the modules, as it should be. They are both communicating and displaying data using the event aggregator and the binding mechanisms of WPF. There are some differences between how WPF and Silverlight approach some issues. The Prism library brings some classes to complement the subset of functionality in Silverlight that are not needed in WPF. However, one can still use those for WPF applications, making a transition from WPF to Silverlight or a mixed project more easily maintained.

The video walkthrough (as well as my own text summary) are based on the rather new Model-View-ViewModel pattern, which many people call a flavour of MVC. It was created specifically for WPF/Silverlight in order to separate behaviour from user interface.

Expect more on this as soon as I unravel it myself.

This is only a bookmark. If you want to know how to do this, read this link from Microsoft: Walkthrough: Using ASP.NET Routing in a Web Forms Application.

Well, you might laugh out loud when you read this, but it is an achievement for me. I wanted to update a table (table A) which had a connection to another table (table B) through a many to many table (table A2B). I had changed A2B to link A to a new table C. I wanted to reflect that change in my Entity Model.

So the first step was to right click on the model and do an "Update Model from Database". Then went through all the steps and clicked Finish. Now entity A has both a collection of Bs and a collection of Cs. I wanted to delete the B collection but, to my chagrin, no delete option was available.

The epiphany came when I managed to select the graphical link from entity A to entity B. The link has the delete option! Which, I have to admit, does make sense. So whenever you want to remove an association between entities... well, select the association and delete it, not the entity properties.

and has 0 comments
I was trying to do something that is usually a drag: create a query with variable parameters. Something like Google search, where each query has a number of words and you want to search for each of them. How can one do this with Linq? More than that, Linq to Entities, which is pretty much making my life hell nowadays.

The idea would be to start with a IQueryable object and keep adding queries to it. This isn't so bad when you want to do an AND operation between your individual query strings.
var dc=new MyEntities();
var content=dc.Content;
foreach (var filter in filters) content=content.Where(c=>c.Text.Contains(s));


But what if you want to do an OR operation? Then you would want to be able to add stuff to the lambda inside a singe Where method. I won't get into the details, rather give you a link. I am not an expert on this myself, so it would be pointless. The more important thing is that you can do this a lot easier by using a library called LinqKit, which adds some very useful extension methods for Linq, enabling you to dynamically create queries, lambdas, etc.

There are other 'lighter' versions of this method on the Internet, unfortunately most of them are usable only with Linq to SQL, not the Entity Framework. For example I've read an interesting blog entry about this, tried the code, and got an ugly error: "The LINQ expression node type 'Invoke' is not supported in LINQ to Entities". LinqKit also did this in its earlier versions, but the Albahari brothers fixed it. So, as far as I can see, I recommend this library for real life linq composition.

The scenario is this: You use a ScriptManager, a TextBox and a Button and your project is at least referencing the Ajax Control Tookit library. You expect when pressing Enter in the TextBox to get to the button Click event. Instead you get the Microsoft JScript runtime error: ‘this._postBackSettings.async’ is null or not an object javascript error.

I found the solution here: JScript Exception in AJAX Control Toolkit. Basically, put the textbox and the button in a Panel and set the DefaultButton property to the button id.