在代码隐藏中使用 StaticResource 和 x:Static

Using StaticResource and x:Static in code behind

我喜欢this flat button style:

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

正在尝试在后面的代码中创建这样的按钮:

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

将抛出:

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.

根据您的工作代码,它应该如下所示:

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

换句话说,去掉引号。 ButtonStyleKey 不是名称,那是静态的 属性 那个 returns 一个具有正确名称的字符串。