To simply quote and link: Unfortunately, this is where the SharedSizeGroup method breaks down. If you want to have a shared Grid that uses the whole available width and automatically adjusts when that space changes you're going to need a different method. A column set to * in a shared group acts just like an Auto column and won't fill or stay within the given space. Taken from John Bowen's blog.

I've finally finished the book WPF in Action with Visual Studio 2008 by Arlen Feldman and Maxx Daymon. Simply put, it was a great book. Most of the programming books focus too much on structure, resulting in very comprehensive information, but giving one little in the way of actual work. WPF in Action is describing features while using them in a few applications that are built almost entirely out of code printed in the book. I think this is the second book any beginner in WPF should read, the first being one of those boring comprehensive ones :)

The book goes from a brief history of Windows Forms and WPF to Hello World in part one, then to describing layouts, styles, triggers, events and animations in the second part. The third goes to create a wiki application using commands and binding, datatemplates, converters, triggers, validation, then custom controls and drawing (including 3D!). I am a big fan of the MVVM pattern, but I liked that in this book, while it got described, it didn't suffocate the other topics, getting only a small subchapter in the binding section. The fourth part explains navigation, XBAP, goes briefly through ClickOnce and Silverlight, then has a large chapter about printing (too large, I believe). The book finishes with transition effects, interoperability with Windows Forms and threading.

All in all I think it was a very nice read. The authors clearly have a lot of experience and are quite qualified to talk not only about the features in WPF, but also the gotchas and some of the problematic implementations or even bugs. The fourth part of the book was a bit of a bore, though. After a pretty heavy 3D drawing ending of part three, I get to read a whole lot about really boring stuff like printing. I am sure that when need arises, though, this is the first book I will open to see what they did.

Bottom line: First three chapters are a must read. Maybe skip the 3D drawing part the the end of part three. The fourth is optional. The authors themselves said that they intended to write something that could be used as a reference, and I think they succeeded. So read the table of contents and see which parts of WPF you are really interested in in those optional parts.

The WPF in Action with Visual Studio 2008 link goes to the publishers site, where you can download the source code and even read some sample chapters.

I am only linking to this blog post that shows how to instantiate the converters directly in the binding, without having to define a resource just for that.

WPF Quick Tip: Converters as MarkupExtensions

Update: After careful deliberation I've reached the conclusion that instead of custom converters that would have to be instantiated in the binding XAML I can just create new binding types. Here is how you can do it:
  1. Inherit from Binding
  2. Implement IValueConverter
  3. Set Converter=this in the constructor
  4. Use the new binding where you see fit


Actually, I have created a more complex Binding object that chooses the type of conversion based on an enumeration or, alternatively, gets converters as content and pipes them one after the other for a more dynamic reuse of converter power. I am still not sure which of these two solution I will use more often, though.

I was trying to add some content to Infragistics WPF controls and some of the images used were blurry. I have tried setting SnapToDevicePixels, but to no visible effect. I did stumble upon a property in the Infragistics.Windows.Utilities class, called SnapElementToDevicePixels. I didn't know what it does, but I tried it anyway. Voila! The image got crisp and clear.

This is the comment from the property in the Infragistics WPF sources:

/// <summary>
/// SnapElementToDevicePixels Attached Dependency Property
/// </summary>
/// <remarks>
/// <p class="body">The SnapsElementToDevicePixels is meant to be used on elements such as an Image that
/// does not currently support SnapsToDevicePixels.</p>
/// <p class="note"><b>Note:</b> The RenderTransform of the element is used so you should not set the RenderTransform
/// on the same element on which you are setting SnapElementToDevicePixels to true. You may set the RenderTransform on
/// an ancestor element. Also, you should not set this property on an element that is an ancestor of one or more
/// elements that have this property set to true. In such a case the results are undefined since the child element's
/// RenderTransform could be calculated before that of the ancestor element. Since this property should be set on
/// discrete elements such as an Image, this scenario should not be required.</p>/// </remarks>

In order to use it, make sure you load the Infragistics.Windows namespace in your XAML:

xmlns:Windows="clr-namespace:Infragistics.Windows;assembly=Infragistics3.Wpf.v9.2"

and then set the Windows:Utilities.SnapElementToDevicePixels property to True.

I had this control that functioned as a textbox. The request was that it behaved differently when used as an editor in a grid and was in the "add new record" line. I agree that the best solution would have been for the grid to set a property to the editor when placing it somewhere or at least when adding to the grid, but that is not relevant.

The solution was, of course, to add a DataTrigger that would check a property of the parent grid row object, by using RelativeSource and FindAncestor. However, that approach resulted in an ugly binding error in the Visual Studio debug view window when the textbox was being used stand alone. It didn't break execution, but I kind of disliked it.

The solution, at first, was to use a Converter. However, the converter class does not apply to the RelativeSource, but to the referenced property. The binding would first look for the parent row, find nothing, then return a null reference exception when trying to access the path property.

Another solution would be to look for the parent in the LayoutUpdated event (only the first time) then look for the trigger and enable or disable it. Yet another is to reference a property that the textbox would set depending on the parent found above. Both solutions would be cumbersome if you don't have ownership of either control.

It appears that there is no way to determine the way a relative source is found. I don't know if they changed that in the WPF4 implementation, but it would have been a nice touch. That being said, I believe one can create a custom Binding object to take care of this. I will update the post with some sources when I get to working with WPF again.

Update: I've reached the conclusion that the problem is the question, not the answer. In order to make an element have a certain behaviour when a child of another element, a style should be added to the resources of the parent. This way, the problem is solved. I agree that sometimes it is cumbersome to do so, but the alternative is that your control will always search for a parent that might not be there. So, the solution is to make the parent make the child do what you want.

I was testing this WPF application on different operating systems and I have noticed that on Windows 2003 the access key letters in labels were always shown as opposed to the other operating systems where only by pressing Alt you could see the shortcut keys.

Apparently unrelated, there was another difference between Windows 2003 and other operating systems: clicking on elements would show their focus styling, while on any other, one needed to navigate using the keyboard Tab. This until I noticed that pressing Alt made the focus style appear on controls that I had clicked on.

Yes, the two are related and are linked to an operating system option that apparently cannot be changed on an application level. In Windows XP go to en empty area of the desktop, click Properties, go to the Appearance tab and click on the Effects button. Both the behaviors described above can be enabled or disabled by unchecking or checking Hide underlined letters for keyboard navigation until I press the Alt key. Here is the Microsoft link with instructions on how to do it.

In WPF, removing the visual focus to a control is as simple as setting the FocusVisualStyle property to {x:Null}, however there doesn't seem to be a way to enable or disable access key underscore.

Others have noticed this behavior, and people have suggested using the WM_CHANGEUISTATE Message on the window to set this functionality, by setting/unsetting the UISF_HIDEFOCUS flag. I have not tried it, though.

One can also try to change the setting in the registry. It seems the key is HKEY_CURRENT_USER\Control Panel\Desktop\UserPreferencesMask and if you want to hide the key focus and the label underline until you press alt you should unset the flag 20H from the first byte in the key.

I started my WPF application and I got this weird exception: Internal error: internal WPF code tried to reactivate a BindingExpression that was already marked as detached. At the time of this entry, googling for this yields about 3 results, only one saying something about how internal WPF errors are usually multithreaded exceptions and, if you have it, try to remove IsAsync="True".

Needless to say, I didn't have that. The StackTrace of the exception was showing me, kind of obliquely, that the error was coming from a binding, but not why. Luckily, I looked in the Visual Studio Output window while getting the error. And there it was! A completely different error, this time telling me what the problem was.

Incidently, the error was caused by a style that had a BasedOn="{x:Type Something}" property setting. I know it is supposed to work, but in this case, it didn't, and it needed the more conservative yet safer BasedOn="{StaticResource {x:Type Something}}".

The cause of the error is only a detail, though, as the lesson here is to always look in the Output window while debugging WPF applications, even if you have an exception thrown. The messages there are more verbose and are actually telling you what bindings do, not what internal code is executed.

I had this scenario where a property was attached to objects but I wanted different default values for different objects. The code made it easy to just check if the property was set or not, then set the default myself. In order to do that, use the DependencyObject.ReadLocalValue instead of DependencyObject.GetValue and then check if the result equals DependencyProperty.UnsetValue. Like this:

return element.ReadLocalValue(MyProperty) == DependencyProperty.UnsetValue;
Of course, this can be used as an extension method for any element and/or property.

Short answer: you can't! The color of the text selection (not of the background) is given by an (internal) class System.Windows.Document.CaretElement, inheriting from Adorner. Here is the bit of crappy code that makes this impossible:

protected override void OnRender(DrawingContext drawingContext)
{
if (this._selectionGeometry != null)
{
Brush brush = new SolidColorBrush(SystemColors.HighlightColor);
brush.Opacity = 0.4;
brush.Freeze();
Pen pen = null;
drawingContext.DrawGeometry(brush, pen, this._selectionGeometry);
}
}

And you might be thinking that it is a simple template change issue and if you don't add the bloody caret to the template it will work. Wrong! The Caret element is instantiated via code in classes as TextSelection, as an implementation of the ITextSelection interface which only has a getter for the Caret property. The TextSelection class is instantiated in all the controls that support text selection as internal properties or fields. Yay!

So unless you recreate the entire selection functionality, you are stuck with the SystemColors.HighlightColor color for selection. As Dr. WPF himself says: "It is entirely impossible in the current .NET releases (3.0 & 3.5 beta). The control is hardcoded to use the system setting... it doesn't look at the control template at all."

Better luck in WPF 4.0... maybe.

WPF is great for styling. They even included different default styles for each Windows operating system so that the controls look "native". So making an application look as if native to the operating system is not a problem. But how can one do the opposite: force the application to always display as if on a specific operating system?

The solution is to include the default theme for that OS in the resources of your application, window, user control, etc, so one can even style different parts for different operating systems, if need be.

Well, this is how you can make you application use the Vista/Windows7 Aero interface. In you App.xaml add an Application.Resources block and a ResourceDictionary with the source /PresentationFramework.Aero, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/aero.normalcolor.xaml. If you have already a style in your application resources, add the resource dictionary in a ResourceDictionary.MergedDictionaries block. Like this:

<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary
Source="/PresentationFramework.Aero,
Version=3.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35,
ProcessorArchitecture=MSIL;component/themes/aero.normalcolor.xaml"
/>
<ResourceDictionary Source="/My.Namespace;component/Themes/MyApplication.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>


The operating system theme files that you can choose from are:
AssemblyTheme file
PresentationFramework.Aeroaero.normalcolor.xaml
PresentationFramework.Classicclassic.xaml
PresentationFramework.Lunaluna.homestead.xaml
PresentationFramework.Lunaluna.metallic.xaml
PresentationFramework.Lunaluna.normalcolor.xaml
PresentationFramework.Royaleroyale.normalcolor.xaml


Of course, the method of loading the theme might be through code, and so this can be used to programatically and dynamically change the theme:

protected override void OnStartup(StartupEventArgs e)
{
Uri themeUri = new Uri(myThemeUriString, UriKind.Relative);
ResourceDictionary theme = (ResourceDictionary)Application.LoadComponent(themeUri);
Resources.MergedDictionaries.Add(theme);
}
base.OnStartup(e);
}

The WPF Infragistics controls 9.2 feature a grid called the XamDataGrid, which has a lot of options and is better designed than the horrible web grid from the same company. I wanted to bind the grid to a DataSet, one that has two tables (Data and Details) that are connected through a data relation (named keyRelation). Also, the fields are not auto generated, but defined in the FieldLayouts block.

First step: define the field layouts. Then bind to the DataSet. No go. The only way I could see anything was if I bound to the first table in the dataset (Data). Even so, the fields that were shown were those from the second FieldLayout definition, not the first. After googling a while I finally found the answer: you need to have a Visible field that has the name of the data relation.

So, the final solution for binding a DataSet hierarchically to a XamDataGrid when AutoGenerateFields is set to false:
  1. Bind the XamDataGrid DataSource to the parent table (or its DataView)
  2. Define two FieldLayout sections in the FieldLayouts block for each of the tables
  3. Add a Field with the same name as the data relation between the two tables to the parent table FieldLayout block


Example:

<DataPresenter:Field Name="keyRelation" Visibility="Visible"/>

For a few weeks I have been having problems running Silverlight on my machine, especially since I had SL3 installed and also Expression Blend, version 3. I didn't mind much, because I don't need Silverlight most of the time. But since sometimes I do, here is the solution for the "Your Silverlight developer components are out of date" error when trying to install Silverlight.

Go to http://go.microsoft.com/?linkid=9394666 and install the Silverlight tools. Yes, they are version 2. No, I don't know why Silverlight 3 would have problems because of version 2 Silverlight tools. However, installing the tools solved my problem.

This will be a long article, one that I intend to add on while understanding more about the MVVM pattern and patterns in general. Also, while I am sure I will add some code during the development of the post, this is intended mostly as a theoretical understanding of the said pattern.

For an easy and short explanation of the concepts, read this article: WPF Apps With The Model-View-ViewModel Design Pattern.

The start of every concept research these days seems to start with Wikipedia. The wiki article about Model View ViewModel says that MVVM is a specialization of the PresentationModel design pattern introduced by Martin Fowler specific for the Windows Presentation Foundation (WPF). Largely based on the Model-view-controller pattern (MVC).
Further reading from Martin Fowler's site on the MVC pattern, which seems to stand at the core of all this specialization, revealed this: Probably the widest quoted pattern in UI development is Model View Controller (MVC) - it's also the most misquoted. [...] In MVC, the domain element is referred to as the model. Model objects are completely ignorant of the UI. [...] The presentation part of MVC is made of the two remaining elements: view and controller. The controller's job is to take the user's input and figure out what to do with it. There is a lot more there, about how in the early MVC concept there were no events or binding of any sort. Instead the controller would get the input from the UI, update the model, then the View would change as the model changes using some sort of Observer pattern. Even from these few quotes, one can see that in this "holy trinity" there are actually two basic actors: the Model (which, to make it easier to differentiate later on from other models, I will call Data Model) and the Presentation (controller+view in MVC).
Let's see what the PresentationModel pattern is all about: Presentation Model pulls the state and behavior of the view out into a model class that is part of the presentation. The Presentation Model coordinates with the domain layer and provides an interface to the view that minimizes decision making in the view. The view either stores all its state in the Presentation Model or synchonizes its state with Presentation Model frequently. As I see it, it introduces a new model, one specific to the Presentation side but independent of the UI controls. Martin Fowler specifically says about the PresentationModel pattern: Probably the most annoying part of Presentation Model is the synchronization between Presentation Model and view. It's simple code to write, but I always like to minimize this kind of boring repetitive code. Ideally some kind of framework could handle this, which I'm hoping will happen some day with technologies like .NET's data binding. and Presentation Model allows you to write logic that is completely independent of the views used for display. You also do not need to rely on the view to store state. The downside is that you need a synchronization mechanism between the presentation model and the view. This synchronization can be very simple, but it is required.

I also find this article about different Model View Presenter patterns very informative and the diagrams easier to understand than Fowlers UML or whatever that horrible diagraming he uses is :)

This brings us to MVVM. It is basically the PresentationModel pattern, where WPF/Silverlight types of complex binding take care of the synchronization of View and ViewModel. For me, one of the most important aspects of this approach is that the complex interactions between UI components (and that don't involve the data in the DataModel) can be left in the View and completely ignored further down. That makes interchanging Views something very easy to do, as the entire "UI logic" can be separated from the more general presentation logic. In this, I see that the UI becomes a third layer by the introduction of the ViewModel/PresentationModel in between the Data Model and the Presentation.
I have imagined doing this in a Web or stricly Windows Forms environment. As Fowler said, the plumbing required for synchronization between the view and the viewmodel makes it not worth the effort. That is where the WPF Data Binding comes in.

Let's start the MVVM chapter with a simple example. There is a need to search people by using different filters, display the list of found people and give the ability to click a person and see the details in a separate detail pane. The filters can be simple (Google like textbox) or complex (specific role, age, etc searches). The complex filters of the search are hidden in a separate panel that can be shown or not.
An ASP.Net or Windows Forms application would probably create a form containing the searchbox, the additional filters in a panel with a checkbox or button to show/hide it, the details panel with textual information and a grid where the list of people would be displayed. Events would provide all the needed plumbing, with the code executed on them placed in the code behind of the form, changing what was needed. See, the code behind was already an attempt to separate the presentation from code, although the separation was mostly symbolic. One might have employed a flavour of the MVC pattern, creating a separate controller class that would have worked with the data model and the form (as a view) through interfaces. That means a lot of plumbing, anyway.
In WPF, one creates the form, as in the Windows Forms approach above, but then it binds no events (or very few, I will talk about that later). Instead, it uses data binding to link UI components to properties that it expects to find on the object that will be provided to the view as a DataContext, that is the ViewModel. It doesn't know what the format of this object is and, indeed, the properties are found using reflection, which makes this slightly slower than other methods.
What this means is that any code that reacts to a change of a UI component would be placed on an event handler of the property to which it is bound. When the property changes, stuff happens, not when someone clicks a checkbox. This makes the architecture a lot more testable from code, as all a test needs to do is change a property, not perform a click. It also means that a lot of extra plumbing must be done on those properties, for example the ViewModels could implement INotifyPropertyChanged and then notify on any property being changed. Also lists must not only inform on the get/set operations on them, but also on their items, which implies using ObservableCollection, ObservableDictionary, BindingList and other objects that observer their items and notify on change. On the Views, Dependency and Attached properties come into play , and I will link to some explanatory posts later on. They are extremely important in WPF, because they compute the value, rather than store it, but that's another story altogether.
What this also means is that events, in the way there are used in Windows Forms scenarios, are almost a hinderance. Events cannot be bound. If they are handled in bits of code that change properties in the ViewModel, then the code must either have a reference to a specific type of ViewModel, which defeats the whole purpose of MVVM, or to read/write properties using reflection, which means extra plumbing in the View code. Not that this cannot be done, and there are several solutions to that. However, it would be ugly to write a view completely in XAML, binding everything you need to properties that are to be found on the ViewModel, then starting writing code just for a few events. Here is where commands come in.
The Command pattern is an Gang of Four pattern, useful in WPF by providing objects that can be bound and that encapsulate a behaviour that will be executed. Read more about Commanding on MSDN. Many WPF controls exposes events as well as commands for common actions, for example the Button class exposes the OnClick event, but also the Command property (which will be executed on click) and the Clicked property (which will be set on click).
Commands in WPF implement the ICommand interface which exposes the Execute method as well as the CanExecute method. A default WPF button that has a command bound to its Command member will appear as disabled if the CanExecute method returns false, that because the ButtonBae class implements ICommandSource. More about commands when I present the RelayCommand class, which has become quite commonplace in the MVVM world.
A problem is that not all controls have a command for every concievable event. A solution is, of course, to inherit from the control and create your own command for a specific event. It only requires that you handle the event internally, expose a property that implements ICommand and execute that command inside the event handler. This brings the advantage that the control can be reused with minimal changes in the XAML. There are other solutions, one of them is to use Attached Properties. If you don't want an attached property for every event that you use, read this article. A very comprehensive article about the application of Commanding in WPF can be found here: WPF Command-Pattern Applied.

So far so good. Using the concepts above we can separate the UI from the data completely, as the View only uses binding on the Data Model and can be replaced with any other View that binds to existing properties. This pattern can be used on any level, be it the window or the user control level. Controls that are strictly UI, of course, don't need to implement MVVM. There are other aspects that were not covered here, more specific to WPF, like Routed Commands and Events and concepts like global messaging. But since they are not really part of the MVVM idea, I will leave them for other posts.
There is also the question of code. I will not be doing any in the post for now. However, I will be ending this with a few links that seem relevant.

Extra links:
Adventures in MVVM -- Ball of Mud vs MVVM
Hands-On Model-View-ViewModel (MVVM) for Silverlight and WPF
Exploring a Model-View-ViewModel Application; WPF Password Manager, Cipher Text

Another important thing to consider is the myriad MVVM frameworks out there, all of them implementing some helper classes and prewiring of applications. I was talking earlier about the RelayCommand. Imagine you want to create a ViewModel that exposes a Command. That command would need to implement ICommand, therefore being an object that has two methods: one to execute and the other to determine if it is possible. Creating a class for each such command would be tedious. The RelayCommand is a generic class of T (where T is the type of the command parameter) with a constructor that accepts an Action of T and a Func of T. You instantiate it with the methods in your class that are to be used and that is it.

I will update this material with more information as it becomes available and if I have enough time for it.

I was creating this XAML to hold the design of all the controls in a library as a theme (generic.xaml). After a while it just got too big and so I had to use merged dictionaries to split the file into smaller parts.

First problem is that you can't just use the name of the file as the source of a ResourceDictionary, you need to specify the assembly name kind of like this:
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Library.Namespace;component/Themes/OneOfMyControls.xaml" />
Notice the keyword component, which is NOT part of the folder or namespace structure.

The second problem is when you want to use merged dictionaries and then reuse a style key, for example, that you would expect to just place directly in generic.xaml or in the first merged dictionary. You will soon get a "Resource not found" error. Googling, one notices a lot of people having the same problem, but only in the generic.xaml/themes scenario. The solution is to add the common style file as a merged dictionary in each of the dictionaries merged in generic.xaml. That means that if you have 5 controls that use the same style and you have a xaml file for each control and one for the style, you need to add a MergedDictionaries entry in each of the 5 control files and merge the style xaml there.

Attached properties allow you to add new properties and functionality without changing one bit of the code of the affected classes. Attached properties are quite similar to Dependency properties, but they don't need an actual property in the affected object. You have probably worked with one when setting the Grid.Column property of controls inside a WPF Grid.

How does one implement it? Well, any class can have the static declaration of an Attached property for any other class. There are decorative attributes that indicate to which specific classes the property should appear in the Visual Studio property window. The caveat here is that if the namespace of the class has not been loaded by VS, the property will not appear, so it is better to place the class containining the property in the same namespace as the classes that the property is attached to.

Well, enough with the theory. Here is an example:

public static readonly DependencyProperty SizeModeProperty
= DependencyProperty.RegisterAttached(
"SizeMode",
typeof (ControlSize), typeof (MyEditor),
new FrameworkPropertyMetadata(
ControlSize.Custom,
FrameworkPropertyMetadataOptions.OverridesInheritanceBehavior,
sizeModeChanged)
);

[AttachedPropertyBrowsableForType(typeof (TextBox))]
public static ControlSize GetSizeMode(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (ControlSize) element.GetValue(SizeModeProperty);
}

[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public static void SetSizeMode(DependencyObject element, ControlSize value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(SizeModeProperty, value);
}

In this piece of code I have just defined a SizeMode property for a class called MyEditor, the default value being ControlSize.Custom. To use it, I would write in the XAML something like MyEditor.SizeMode="Large" and it would attach to any DependencyObject. The FrameworkPropertyMetadataOptions flags are important, I will review them later on. This also declares a sizeModeChanged method that will be executed when the SizeMode changes.

The GetSizeMode and SetSizeMode methods are needed for the attached property to work. You might also notice this line: [AttachedPropertyBrowsableForType(typeof (TextBox))], decorating the getter, which tells Visual Studio to display SizeMode in the properties window of TextBox objects. Another possible attribute is [AttachedPropertyBrowsableForChildren(IncludeDescendants = true)] which tells Visual Studio to display the property for all the children of the control as well.

Now, how can this be useful? There are more ways it can.
One of them is to bind stuff to the property in Triggers or Templates like this: Binding="{Binding Path=(Controls:MyEditor.SizeMode), RelativeSource={RelativeSource Self}}". This is interesting because one can use in the visual UI properties that are not part of the actual code or ViewModel.
Another solution is to use the change method, but be careful that the method must consider all possible uses for the property and also it will not work for when you explicitly set the default value (as it doesn't actually change)! Let me detail with a piece of code:

private static void sizeModeChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
FrameworkElement elem = d as FrameworkElement;
if (elem == null)
{
throw new ArgumentException(
"Size mode only works on FrameworkElement objects");
}
switch ((ControlSize) e.NewValue)
{
case ControlSize.Small:
elem.Width = 110;
break;
case ControlSize.Medium:
elem.Width = 200;
break;
case ControlSize.Large:
elem.Width = 290;
break;
case ControlSize.Custom:
break;
default:
throw new ArgumentOutOfRangeException("e",
" ControlSize not supported");
}
}


Here I am setting the Width of a control (provided it is a FrameworkElement) based on the change in SizeMode.

Ok, that is almost it. I wanted to shaed some extra light to the FrameworkPropertyMetadataOptions flags. One that is very important is Inherits. If set, the property will apply to all the children of the control that has the property defined. In the example above I first set FrameworkPropertyMetadataOptions.Inherits as a flag and I got an error, because it would try to set the Width to children controls that were not FrameworkElements like Border.

Another interesting page that is closely related to this is I’ve created an Attached Property, now how do I use it? where an Attached property is used in a Behavior, which is actually implemented by the Blend team and, as such it is still in the Expression assembly. Here are two other pages about this:
Using a Behavior to magnify your WPF applications
The Attached Behavior pattern.