Friday, December 19, 2008

Coding WPF styles in C#

WPF styles let you specify the look of your controls consistently across your application.  Today I needed to create menu items in a different part of the application based on the currently focused element.
I got the menu creation code to work, and then wanted to apply my WPF style instead of typing a bunch of header names in and then maybe having to change them later.

Here is the WPF style:
<Style x:Key="{x:Type MenuItem}" TargetType="{x:Type MenuItem}" BasedOn="{StaticResource {x:Type MenuItem}}">
<Setter Property="Header" Value="{Binding Command.Name, RelativeSource={RelativeSource Self}}"/>
<MenuItem Command="ApplicationCommands.Cut"/>

Here is the C# equivalent:

new returnValue = ContextMenu();
//base our style on the current MenuItem Style. No need for null check.
var headerStyle = new Style(typeof(MenuItem), TryFindResource(typeof(MenuItem)) as Style);
var commandNameBinding = new Binding("Command.Name");
commandNameBinding.RelativeSource =
headerStyle.Setters.Add( new Setter(HeaderedItemsControl.HeaderProperty, commandNameBinding));
returnValue.Resources.Add(typeof(MenuItem), headerStyle);
returnValue.Items.Add(new MenuItem() { Command = ApplicationCommands.Cut });