2

我有一个资源字典,其中包含程序控件的所有自定义样式。字典与应用程序的资源合并,如下所示:

    <ResourceDictionary x:Key="Controls">
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Controls.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>

我可以通过 xaml 轻松访问不同的样式:

<Button Style="{StaticResource Button}" />

但是,每当我尝试通过代码分配具有这种样式的控件时,它都会失败。

我试过了:

    Button.Style = Application.Current.Resources("Button")

    Button.Style = CType(Application.Current.Resources("Button"), Style)

以及与上述类似的不同方法。在测试一些获取样式的不同方法时,我遇到了“找不到资源”,但是当使用上述方法时,程序似乎找到了样式。我可以成功运行该程序 - 但没有任何视觉证据证明确实应用了该样式。

如何正确地为控件分配在资源字典中找到的样式?

4

2 回答 2

5

For any descendants: here is how I succeded to apply a style from a resource to a dynamically created control through code. (Given that you have a Resource Dictionary containing the style)

First step: Include the Resource Dictionary

To make a Resource Dictionary easily accessible from code, add it through code.

VB

  Dim myResourceDictionary As New ResourceDictionary
  myResourceDictionary .Source = New _
  Uri("/YourApplication;component/YourDictionary.xaml",
        UriKind.RelativeOrAbsolute)

C#

   var myResourceDictionary = new ResourceDictionary
       {
           Source = new Uri("/YourApplication;component/YourDictionary.xaml", UriKind.RelativeOrAbsolute)
       };

Replace "YourApplication" with your solution name, and "YourDictionary" with your Resource Dictionary file.

Second step: Assign the Style

To make use of the newly imported Resource Dictionary, simply assign a control a style;

VB

  Dim myButton As New Button
  Dim myButtonStyle As Style = myResourceDictionary("YourStyleKey")
  myButton.Style = myButtonStyle

C#

  var myButtonStyle= myResourceDictionary["YourStyleKey"] as Style;
  var myButton = new Button { Style = myButtonStyle };

Special thanks to user Stefan Denchev for giving me an article covering this. As C# isn't my strong side, please edit this if I've made any mistake.

于 2013-09-16T13:56:36.227 回答
5

使用 Application.Current.Resources["Button"]。

于 2013-09-16T05:39:40.903 回答