Search code examples
c#wpfcode-behindmarkup-extensions

Using StaticResource and x:Static in code behind


I like this flat button style:

<Button Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" BorderThickness="0" ... />

Trying to create such button in code behind:

var button = new Button
{
    Style = (Style)Application.Current.FindResource("ToolBar.ButtonStyleKey"), // wrong
    BorderThickness = new Thickness(0),
    ...
};

Will throw:

An exception of type 'System.Windows.ResourceReferenceKeyNotFoundException' occurred in WindowsBase.dll but was not handled in user code

Additional information: 'ToolBar.ButtonStyleKey' resource not found.


Solution

  • According to your working code, it should look like this:

    Style = (Style)Application.Current.FindResource(ToolBar.ButtonStyleKey)
    

    In other words, ditch the quotes. ButtonStyleKey is not the name, that's the static property that returns a string with the right name.