and has 0 comments
A while ago I wrote a post detailing how to install Windows XP on a laptop with SATA drivers without using any floppy disk. Today I had to do such installation again and I've met with some annoying errors.

The laptop was an Acer Aspire, so I did everything in my old post and started the computer. It is important to use the correct drivers, as in my case the installation met with a blue screen with code 0x0000007B. It was like it tried to use some of the SATA drivers I had loaded on my WindowsXP CD, but not the right ones.

After the installation went ok, Windows XP would not boot up, not even in safe mode. In order to check what the hell is going on (because the default behaviour is to show a blue screen and immediately reboot) you need to start the computer and press F8, then disable the automated restart in case of error from the menu.

The problem is that the laptop had "AHCI mode" enabled in BIOS. Apparently, Windows XP doesn't support this mode. Set it to IDE BEFORE you start installing Windows XP. After that, you can enable AHCI after you install some stuff and change some registry entries, but it seems XP doesn't really have much use of this mode of access anyway. Here is a forum discussing this, but I haven't got around to trying the things described there yet.

Good luck with your installation. I almost went for installing Windows 7. Phew!

Ok, I am working on the blog to make it more accessible. I've replaced the template, I made all changes in the template from javascript and CSS, not by editing it and I've removed many of the things clogging the site. Not the cats and flies, though :) The light (low band) version of the site is not working anymore. If you want just the content, you can open the RSS feed.

I would like to know what you are thinking about the new look and I hope I will find the time to write interesting posts.


I almost expected the guy to be Canadian. :) This series of fantasy books is a masterpiece of writing. Not only it is complex of plot and emotion, but the characters are many, diverse and (most of all) different.

So far, the A Song of Ice and Fire saga, written by American author George R. R. Martin, consists of four books, the first published in 1996 and the last in 2005. At least three other books are planned in this series. The plot is a historical fantasy, but one unlike the books I've read recently. The aspects of magic and otherworldiness are rare, the bulk of the writing being about the feudal world, with kings, knights, low borns, maidens and whores, thieves, rapists and murderers, plotters and honorable men. No wonder that, lacking a lot of special effects, the story has been selected as the basis for a TV series.

But what is more important than anything is that the writing is really good. The characters are all human, with needs, desires, qualities and faults. You can't help but empathise with them, only to suffer at the cruel fate the writer bestows upon them. Not one escapes unscathed from the malice and pettiness of other people or from shere bad luck. You get to like the characters, then Martin fucks them up. I really wanted to use a more elevated language here, but it's the truth: the world he depicts seems horribly real, not a fairy tale of valiant white knights and pure maidens, but of ridiculous people grabbing lustfully whatever life offers them as it is unlikely their fortune is going to last long.

For the bad part, though, I think the author went too deep, got himself responsible for a lot of characters that he must now move forward, in gruesome detail. The fourth book became so large that he had to split it. He did so by character and geography, rather than by time, so a lot of the characters were missing from the fourth book, A Feast for Crows, and left for the fifth, but acting in the same timeline. At the end of A Feast for Crows the author explains his decision to not just split the book in the middle with a "To Be Continued" ending, and hopes for a publication of the second half in a year. That was in 2005. Ahem.

A lot of people are a bit confused by the long wait for the fifth book. Martin keeps making promises that he doesn't keep and, in July this year, he announced that A Dance with Dragons is already 1400 pages long and 5 chapters close to completion. I hope he does finish it quickly enough, although that would only prolong my suffering anyway. I am sure the fifth book will be as brilliant as the others, but then I will have to wait another 5 years for the sixth. I know TV series usually have no plot, but at least they come weekly ;)

Bottom line: The books are great, I recommend them to any lover of fantasy or even historical novels. I can hardly wait for the TV series, A Game of Thrones, as well.

and has 2 comments
While waiting for the tenth book in the Malazan Book of the Fallen saga, I went and read Prince of Nothing, by another Canadian author, R. Scott Bakker. This is a three book story, first published in 2004, about what I can only describe as a psychopath, member of a rationalizing sect, going out into the world to protect the secret of said sect.

The book is well written, although not nearly as brilliant as the Malazan series. However the subject of it is very interesting, at least from my standpoint. It concerns a human that is trained in the ways of mental manipulation, rationale and causality, something akin to the Vulcans from StarTrek, but with a very human side to it, the one that pushes one to amass power and use their knowledge to manipulate.

No wonder that the "prince of nothing" is the central character in the books, but not the main character, the role being left to a sorcerer, a man that is at the same time keeper of arcane knowledge and the scorn of ordinary humans. I can't help but empathize with the guy: basically a geek in love with a whore, while a psychopath destroys his world with insidious manipulation. ;)

There is another central character to the story, an insane barbarian, like a tortured Conan, who is both terrifyingly strong and ridiculously fragile, both a mindless warrior and a brilliant strategist. He is also, like Achamian the sorcerer, an exponent of humanity.

Prince of Nothing is a very smart book, one that can only get better as the writing skills of Scott Bakker improve. Its assets are both a scientific approach to the human psyche and a veritable intrigue of arcane powers in conflict with each other on the background of huge masses of clueless people. The plot itself is similar to the story in the Berserk manga, at least its start, where the strong warrior chooses to follow the charismatic and ambitious leader only to his doom. The moral, as I saw it, is that while we choose to live our lives with eyes closed, we cannot in good conscience pretend to deserve control over what happens to us.

I hope the series, known as "The Second Apocalypse", continues, since Prince of Nothing raised more questions than gave answers and the plot really caught my attention. A nice book that I warmly recommend.

I haven't been the most present of hosts, but then again, I haven't seen much interest for the collaboration page, with its open chat and whiteboard. Therefore I replaced the link to it with the Plugoo chat. The blog desperately needs some refactoring, but not likely that it will happend soon.

I was working on this application and so I found it easy to create some controls as UserControl classes. However, I realised that if I wish to centralize the styling of the application or even move some of the controls in their own control library with a Themes folder, I would need to transform them into Control classes.

I found that there are two major problems that must be overcome:

  1. the named controls in a user control can be accessed as fields in the code behind; a theme style does not allow such direct access to the elements in the control template.
  2. the controls that expose an event may not expose an associated command. In a user control a simple code behind handler method can be attached to a child control event, but in a theme a command must be available in order to be bound.



Granted, when the first problem is solved, it is easy to attach events in the code of the control to the child elements, but this presents two very ugly problems: the template of the control will need to contain the child elements in question and the event will not be declared in the theme, so the behaviour would be fixed as well.

I will solve the handling of events as commands by using a solution from Samuel Jack. The article is pretty detailed, but to make the story short, one creates an attached property for each of the handled events by using a helper class:


public static class TextBoxBehaviour
{
public static readonly DependencyProperty TextChangedCommand =
EventBehaviourFactory.CreateCommandExecutionEventBehaviour(
TextBox.TextChangedEvent, "TextChangedCommand", typeof (TextBoxBehaviour));

public static void SetTextChangedCommand(DependencyObject o, ICommand value)
{
o.SetValue(TextChangedCommand, value);
}

public static ICommand GetTextChangedCommand(DependencyObject o)
{
return o.GetValue(TextChangedCommand) as ICommand;
}
}

then by using a very simple syntax on the control that fires the event:


<TextBox ff:TextBoxBehaviour.TextChangedCommand="{Binding TextChanged}"/>



The problem regarding access to the elements in the template is solved by reading the elements by name from the template. In some situations, like when one uses a control as a source for a data control (like using a TreeView as the first item in a ComboBox), the approach will have to be more complicated, but considering the element is stored in the template of the control, something like this replaces the work that InitializeComponent does inside a UserControl:


[TemplatePart(Name = "PART_textbox", Type = typeof (TextBox))]
public class MyThemedControl : Control, ITextControl
{
private TextBox textbox;

public override void OnApplyTemplate()
{
base.OnApplyTemplate();
textbox = Template.FindName("PART_textbox", this) as TextBox;
}
...


The code is pretty straight forward: use the FrameworkTemplate.FindName method to find the elements in the OnApplyTemplate override and remember them as fields that you can access. The only weird part is the use of the TemplatePartAttribute, which is not mandatory for this to work, but is part of a pattern recommended by Microsoft. Possibly in the future tools will check for the existence of named elements in the templates and compare them against the ones declared in the control source.

The code of a demo project can be downloaded here.

Some other technologies I have used in the project:

  • the RelayCommand class, to make it easier to defined ICommand objects from code without declaring a type for each.
  • the AccessKeyScoper class that allows an IsDefault button to act locally in a panel.

If you google the net for using visual effects in WPF you are very likely to hit BitmapEffects. Well, bad news, BitmapEffect is obsolete and broken in WPF4. Instead you have Effect. The idea is to write (or download) a custom Effect for the things one would normally do using the slow (but easy to use) BitmapEffects. Also, the BitmapEffectGroup doesn't work anymore and has no alternative in WPF4. Bummer! According to Dr. WPF, the framework will try to automatically translate the older BitmapEffects to the new ones. That applies for BlurBitmapEffect and for DropShadowBitmapEffect with a Noise level of 0, for the others... you are on your own.

There were 5 default BitmapEffect classes in WPF3:
  1. BlurBitmapEffect - the WPF4 alternative is BlurEffect
  2. OuterGlowBitmapEffect - the WPF4 alternative in the Microsoft article is BlurEffect, but I have found that it can be replaced by DropShadowEffect with ShadowDepth set to 0
  3. DropShadowBitmapEffect - the WPF4 alternative is DropShadowEffect
  4. BevelBitmapEffect - the WPF4 alternative is a custom class inheriting from Effect.
  5. EmbossBitmapEffect - the WPF4 alternative is a custom class inheriting from Effect.


I found this project when googling to a simpler way of building ShaderEffects: WPF ShaderEffect Generator. Also, a discussion about a Bevel ShaderEffect here led me to this WPF shader library, but it's last release date is somewhere in March 2009.

I am using this WPF control that looks like a headered panel. On the header there is a menu, a button and then, underneath, some content that could be anything. I had this request that, when using the Tab key to navigate, the focus should first come to the button, which is not the first control in the header, then jump to the controls in the content and then jump back to the menu. In other words, to make the menu the last controls that can be reached via the Tab key inside this WPF control.

Well, in WPF there is this class called KeyboardNavigation which has some very useful attached properties: TabIndex (which defaults to int.MaxValue) and TabNavigation (which defaults to Continue). As in Windows Forms, one needs to set the TabIndex to control the navigation order, but the TabNavigation property makes it a lot more versatile and clear as well. In my case, I had to do the following:
  1. Set the entire panel control to KeyboardNavigation.TabNavigation=Local. That allowed me to control the tab index inside the control, otherwise the TabIndex value would have been global to the window
  2. Set the TabIndex of the button to 1. That made the button the first thing to be selected in case I use Tab to navigate in the panel
  3. Set the TabIndex of the content to 2. This set the controls in the content as the next controls to be accessed via the Tab key
  4. Set the TabNavigation value of the content to Local. Without this, the TabIndex value would have made no sense. First of all the content panel has IsTabStop to false and, second, any control inside it would have int.MaxValue set as TabIndex which would work globally in the main control.


This example should make it clear how to use the KeyboardNavigation properties. There is one more, called ControlTabNavigation, which has a misleading name and an ambiguous description. It is not related to a control, the Control in the name comes from the Ctrl key. In WPF one can use Ctrl-Tab to navigate an alternative order thus allowing, in this case, to go directly to the menu, then the button and then the controls in the content area.

I was trying to use a static class of attached properties that I would use inside my WPF control templates, so that every time I need to change them I would only use a setter, not copy paste the entire template and make minute changes. It worked great and I recommend this solution to everybody. So after the refactoring of my control I was shocked to see that in the production application, all my attached properties were throwing binding errors!

The solution was to explicitly use the Path= syntax in the bindings.

{Binding Path=(namespace:ClassName.Property)...
not
{Binding (namespace:ClassName.Property)...

The strange thing is that in the test application everything worked great, so what went different? Apparently the problem is that IXamlTypeResolver (used in PropertyPath) is not finding namespaces unless already registered, as explained here by Rob Relyea. The dude with that Lovecraftian name is the program manager for the WPF & Xaml Language Team.

So if one uses the namespace of the attached property before in some other context or by using the verbose syntax before, it works even with the Path keyword omitted. Not really sure why the verbose syntax works differently though.

Many a time I want that textblocks that get trimmed to display their text as a tooltip. For that, I would make a trigger to set the Tooltip value to the Text value if the textblock has been trimmed. The problem is that there is no property that shows if this is the case.

Googling a bit, I found this article, which apparently works, but also has some problems, as reported by many commenters. Even if it would have worked perfectly, my scenario is too simple to need all that code.

The idea of the original post is simple and I like it, the problem being that convoluted method that computes the width of the text in the textblock. Why would I want to redo all the work that is being done by the framework itself? The width of a textblock with TextWrapping NoWrap should be textBlock.Measure(Size(double.MaxValue,double.MaxValue)). I am sure a more complex scenario can also be serviced by this method, if the height is taken from the TextBlock, but I don't need it.

So here is the entire class, using my measuring method:
public class TextBlockService
{
static TextBlockService()
{
// Register for the SizeChanged event on all TextBlocks, even if the event was handled.
EventManager.RegisterClassHandler(typeof (TextBlock),
FrameworkElement.SizeChangedEvent,
new SizeChangedEventHandler(OnTextBlockSizeChanged),true);
}

public static readonly DependencyPropertyKey IsTextTrimmedKey =
DependencyProperty.RegisterAttachedReadOnly(
"IsTextTrimmed",
typeof (bool),
typeof (TextBlockService),
new PropertyMetadata(false)
);

public static readonly DependencyProperty IsTextTrimmedProperty =
IsTextTrimmedKey.DependencyProperty;

[AttachedPropertyBrowsableForType(typeof (TextBlock))]
public static Boolean GetIsTextTrimmed(TextBlock target)
{
return (Boolean) target.GetValue(IsTextTrimmedProperty);
}

public static void OnTextBlockSizeChanged(object sender, SizeChangedEventArgs e)
{
TextBlock textBlock = sender as TextBlock;
if (null == textBlock)
{
return;
}
textBlock.SetValue(IsTextTrimmedKey, calculateIsTextTrimmed(textBlock));
}

private static bool calculateIsTextTrimmed(TextBlock textBlock)
{
double width = textBlock.ActualWidth;
if (textBlock.TextTrimming == TextTrimming.None)
{
return false;
}
if (textBlock.TextWrapping != TextWrapping.NoWrap)
{
return false;
}
textBlock.Measure(new Size(double.MaxValue, double.MaxValue));
double totalWidth = textBlock.DesiredSize.Width;
return width < totalWidth;
}
}


This would be used with a trigger, as I said at the beginning of the post:
<Style TargetType="{x:Type TextBlock}">
<Setter Property="TextTrimming" Value="CharacterEllipsis"/>
<Style.Triggers>
<Trigger Property="Controls:TextBlockService.IsTextTrimmed" Value="True">
<Setter Property="ToolTip" Value="{Binding Text,RelativeSource={RelativeSource Self}}"/>
</Trigger>
</Style.Triggers>
</Style>

Today a power outage screwed something in my Visual Studio installation. For the life of me I couldn't figure out what went wrong and I also didn't have the time to properly investigate. The issue appeared when I restarted the computer, ran Visual Studio 2010, loaded a project (any project) and tried to compile. Invariably, an error would prevent me from building the project:Error 22 A problem occurred while trying to set the "Sources" parameter for the IDE's in-process compiler. Error creating instance of managed object 'Microsoft.VisualStudio.CSharp.Services.Language.Features.EditAndContinue.EncState' (Error code is 0x80131604). Application.

I have tried disabling Edit and Continue, I've tried to disable the Exception Assistant and also I've re-registered the dlls in the Visual Studio 10.0/Common7/IDE folder, all to no avail. Even worse, it seemed as I am the only person on Google (yay!) that got this error so I couldn't find a quick no effort solution (boo!). The error code 0x80131604 stands for HRESULT COR_E_TARGETINVOCATION, or a TargetInvocationException, which is thrown by methods invoked through reflection. So that is that.

The solution was to reinstall Visual Studio. It took half a day, but it fixed it. If you have met the same issue and you found a quicker way, please leave a comment.

and has 0 comments
I was posting a while ago about the first album from Hole's bassist, Melissa Auf Der Maur. I found that the music had a haunting femaleness in it and sounded pretty cool. She has recently released her second album Out of Our Minds and my opinion is... that they were! The songs are lame, like a really wattered out version of the first. Lady, if you don't feel like it, wait until the muse graces you with her presence, don't just write crap because you have a deadline. (Let me do that, ahem...)

Moving on to Linkin Park. A refreshing mixture of hip hop and rock, their first albums (Hybrid Theory and Meteora) made them famous. If you don't count the collection of remixes of their previous songs, their third album, Minutes to Midnight, was released after some time had passed (period during which Mike Shinoda was writing hip hop like crazy and the other guy... well, nobody knows what he did), had some environmental messages, some slow music, maybe some Michael Jacksony save the world songs... It pretty much sucked, but it was also ok. I mean, if you want to mellow down a little, just to try it on, why not? So now I got reminded of them when I accidentally saw Transformers and the theme of the film was sang by Linkin Park and called New Divide. It sounded kind of cool, something that resembled their first albums, so I got their latest album, A Thousand Suns, and tried it on. Long story short: it sucked. There were some cool songs, like Wretches and Kings, or Blackout, but overall, it was a whiny piece of crap. Dude! It's called ROCK, you're letting a Japanese hip hopper make you look like an emo kid trying to sing for the highschool prom.

Ok, now for some of the better songs on these albums:

Melissa auf der Maur - Out of Our Minds



Linkin Park - Wretches and Kings

So I have returned from the holidays, but I have still a ton of stuff to organize before I get my mojo back. I will probably start writing entries from next monday, featuring the holiday to Greece, books I've read, TV series that I am watching and, hopefully, something related to programming, too :)

However, I have amassed a few small things that I wanted to say and are minute enough to not deserve their own blog post, so here are some of them:
  • I have watched the British TV mini series called The Deep. It stars lovely Minnie Driver, but the show is utter crap! I couldn't believe how bad it was. So, don't watch it!
  • Internet Explorer 9 beta was released and it is downloadable. However, when trying to install it at home it said I cannot install IE9 on a Windows XP machine and I must upgrade the operating system. Verboten! Here is a hearty Fuck you! from me, Microsoft. When are you going to get that no one prefers Windows 7 to XP?
  • I've finally watched The Expendables. Imagine one of those really low budget TV movies with heroes killing faceless bad guys in huge explosions, only with known people in the underdevelopped and badly written roles. Fail!

and has 1 comment
While looking over Reflector-ed Microsoft code I noticed an attribute called FriendAccessAllowed. I googled a little and I've come up across something called Friendly Assemblies. Basically you want that your code marked as internal be visible to other assemblies that you specify. This way you restrict access for other people, but you don't need to place all your code into a huge assembly.

Microsoft tells us that to do that for .NET you need to use InternalsVisibleToAttribute to make assemblies be friends in either a signed or an unsigned way.

All nice and all, but there is no mention of this FriendAccessAllowedAttribute class. All I could find is a Microsoft patent called Logical Extensions to Intermediate Code, which says extend the runtime's notion of friend assemblies with a "FriendAccessAllowed" attribute, and only include internal methods marked with this attribute in the reference assembly (instead of known implementations in which all internal methods are included in the assembly).. In other words, specify explicitly which of the internal members you want exposed to your friends.

There is another question about this on StackOverflow, which says as much, as well, but nothing actually usable.

As far as I can see, Microsoft uses this in the WPF and Silverlight frameworks only and the funny thing is... the attribute is internal. :)

If you search the net for a skinnable application, you get a lot of answers and pages that seem to hit the spot right on. If you are looking for a skinnable control library, though, the hit count drops considerably. This post is about my adventures with resource keys and the solution for a problem that has plagued me for more than a day of work, plus some weird behaviour that I have as yet no explanation for.

The article is pretty long, so here is the short and dirty version:
  • Do not use Colors as dynamic resources, use Brushes
  • If you want to use resources from a theme dictionary outside the assembly, you must give them keys of the type ComponentResourceKey
  • The type you use in the constructor of the ComponentResourceKey class or in the markup extension of the same name must be in the same assembly where the resource is!


The scenario is as follows:
  • there is an application that needs to change some of its visual characteristics dynamically during run time
  • the application uses a custom control library
  • other applications/modules should use the same themeing mechanism
  • other applications will use the same control library


The solution seemed simple enough:
  • create a static class to hold the string keys for the resources I want to define dynamically
  • create a shared resources dictionary in the controls theme, using those keys
  • use the shared dictionary in the controls theme
  • create another shared resources dictionary in the applications, or use only the ones already defined in the control library
  • use the application shared dictionaries in the application styles
  • programatically add/remove resources directly in Application.Current.Resources to override the already defined resources


I have tested this solution in a not very thorough manner and found it working. Of course, some of the problems needed solving.

The first issue is that theme level resources are not found from outside the assembly unless defined using a ComponentResourceKey as the key of the resources. This special class receives two parameters in the constructor: a type and an object that is a "regular" resource key. So instead of using a string, as one would probably use in an application style, you use a component resource key that receives a type and that string. A small test confirmed that a resource is not found at the application level using FindResource if only defined with a string as key and that it is found if using a ComponentResourceKey.

The second issue was that in order for a resource to be dynamically changed at runtime it needed to be defined as a DynamicResource, not a StaticResource which is only resolved at compile time. Not a huge problem. However, if one has defined some brushes in the control library and then referenced them in all the styles, then it would also work to redefine those brushes to use colors dynamically, and then all one has to do is change the colors. That would also prove advantageous if one needs a variety of brushes using the same colors, like gradients or some lighter version of the same color.

This leads to Problem number 1: Dynamically changing Color resources worked for foreground brushes, for background brushes, but not for border brushes! So you have a textbox and you define Background, Foreground and BorderBrush properties using StaticResource on brushes that themselves define their Color as a DynamicResource. You change the colors (adding new resources at the application level of the type Color) and you see the Background and Foreground changing, but the border staying unchanged.

I have no idea why that happened. Some information that I got researching this problem was related to Shared resources, but changing the shared status of brushes or even colors to true or false did not change anything. Another idea was that his was related to their Frozen status but, as there was no difference between the Foreground and BorderBrush brushes (I even used the same brush at the same time on both properties), I've decided that it wasn't the case.

BorderBrush is a dependency property belonging to the Border element, while Foreground and Background belong to the TextElement and Panel elements, respectively, and other elements add themselves as owners to them. In the case of the Border element that I have tested this weird behaviour on, BorderBrush is its own dependency property, while Background is the Panel.BackgroundProperty. I also thought that it may have something to do with FrameworkPropertyMetadataOptions.SubPropertiesDoNotAffectRender, but both properties are registered with this flag.

After some searching, I found that the Border element caches internally Pen objects that are used to render the different border sides. They use the same brush as the border, though, and so, even if this is the best candidate for the cause of the problem, I still don't know what the hell was going on.

The solution for this problem was (to my chagrin) to use the brushes themselves as dynamic resources. Well, it was a setback, seeing how the resources I want to change are colors and now I am forced to create brushes and, thus, stain this process with the responsibility of knowing what kind of brushes are needed for my controls and applications, but I could live with it. After all, that was all WPF stuff, so I could separate it at least from the static class holding the keys of the characteristics I wanted to change dynamically.

Problem number 2: using as a key in XAML a class with a long name which uses a constructor that receives a type and a static constant/property of a class is ugly and unwieldy. The solution for this problem was to create another static class that would hold the keys for the brushes. Each brush would have a property in the class that returns a ComponentResourceKey object that uses the classes own type as the first parameter and the constant string key from the static string key class.

That effectively changes stuff looking like {DynamicResource {ComponentResourceKey TypeInTargetAssembly={x:Type UI:ResourceScheme},{x:Static UI:ResourceScheme.ControlBackgroundKey}}} to {DynamicResource {x:Static WPF:ThemeResources.ControlBackgroundBrushKey}}. Still a mouthful, but manageable.

Problem number 3 (the big one): it doesn't work! The brushes I so carefully created in the theme are not getting set in the controls, not the mention the application. What confounded the issue even more is that if I changed DynamicResource to StaticResource in the control templates I would see the brushes rendered correctly. I wouldn't be able to change them dynamically afterwards, but how come StaticResource works and DynamicResource doesn't!? Stranger still, adding/removing resources with the same key in the application resources dictionary (the mechanism that was supposed to dynamically change the aspect of the application) worked! Everything was working perfectly, and only the default brushes defined in the theme were not loaded!

The solution for this was (after hours of trial, error, googling, suicidal thoughts and starting all over again) to use a type from the control library in the ResourceComponentKey constructor! You see, I had placed both static key classes in a separate assembly from the control library. Moving the WPF related resource key class in the control library fixed everything!

Now, you may be wondering why that worked, and so do I. As I see it, if you define a template and a brush in a theme and the template is loaded and applied, then the brush should also be loaded. If FindResource did not find the brush, then it must be that either the brush was not loaded due to some internal requirements of the ResourceComponentKey class or that it was loaded and then the key I was using was different from the one I was using when asking for it or, as Akash Kava tried to explain to me on StackOverflow, it will only find in the resource dictionaries of its own logical parental tree.

I have dismissed the second option, as the ComponentResourceKey has an Equals override that simply compares type and key. There cannot be two instances of the same type and the key is a string constant, so there should be no ambiguity on whether two resource keys are equal.

What remains are that either the ComponentResourceKey class messes things up or that the resources using resource keys are placed in "logical trees" based on the target type of the ComponentResourceKey. I have looked for the usages of the ComponentResourceKey class and all I could find was something in a BaseHashHelper that seemed related to ItemsControl or CollectionView, so I don't think that's it. I also looked at the implementation of FindResource, but found nothing that I could understand to cause this.

As a funny side note, as I was going about this task I was trying to get inspiration from the way the SystemColors class worked. The resource keys related to colors that were returned were not of the type ComponentResourceKey, but of SystemResourceKey, both inheriting from ResourceKey nonetheless. I have noticed no significant piece of code in the (of course internal) SystemResourceKey class, however I did find code in FindResource that checked if the key is of type SystemResourceKey and did something with it. Nice, Microsoft! However, that was not the cause of the problem either.

After knowing what to look for, I did find on the Microsoft article about the ComponentResourceKey markup extension that The TypeInTargetAssembly identifies a type that exists in the target assembly where the resource is actually defined. In the article about the ComponentResourceKey class, they say If you want an easily accessible key, you can define a static property on your control class code that returns a ComponentResourceKey, constructed with a TypeInTargetAssembly that exists in the external resource assembly, and a ResourceId. Too bad they hid this information in the Remarks section and not in the definition of the Type parameter.

Congratulations if you have read so far! You must be really passionate about programming or desperate like me to find an answer to these questions. I hope this article has enlightened you and, if not, that you will find the answers and then get back to me :)