如何定義及參考 WPF 資源 (WPF .NET)

此範例示範如何定義資源並加以參考。 資源可以透過 XAML 或程式碼來參考。

重要

.NET 7 和 .NET 6 的桌面指南檔正在建置中。

XAML 範例

下列範例會定義兩種類型的資源:資源,以及數 StyleSolidColorBrush 資源。

<Window.Resources>
    <SolidColorBrush x:Key="MyBrush" Color="#05E0E9"/>
    <Style TargetType="Border">
        <Setter Property="Background" Value="#4E1A3D" />
        <Setter Property="BorderThickness" Value="5" />
        <Setter Property="BorderBrush">
            <Setter.Value>
                <LinearGradientBrush>
                    <GradientStop Offset="0.0" Color="#4E1A3D"/>
                    <GradientStop Offset="1.0" Color="Salmon"/>
                </LinearGradientBrush>
            </Setter.Value>
        </Setter>
    </Style>
    <Style TargetType="TextBlock" x:Key="TitleText">
        <Setter Property="FontSize" Value="18"/>
        <Setter Property="Foreground" Value="#4E87D4"/>
        <Setter Property="FontFamily" Value="Trebuchet MS"/>
        <Setter Property="Margin" Value="0,10,10,10"/>
    </Style>
    <Style TargetType="TextBlock" x:Key="Label">
        <Setter Property="HorizontalAlignment" Value="Right"/>
        <Setter Property="FontSize" Value="13"/>
        <Setter Property="Foreground" Value="{StaticResource MyBrush}"/>
        <Setter Property="FontFamily" Value="Arial"/>
        <Setter Property="FontWeight" Value="Bold"/>
        <Setter Property="Margin" Value="0,3,10,0"/>
    </Style>
</Window.Resources>

資源

資源 SolidColorBrushMyBrush 可用來提供數個屬性的值,每個屬性都會採用 Brush 類型值。 此資源會透過 x:Key 值來參考。

<Border>
    <StackPanel>
        <TextBlock Style="{StaticResource TitleText}">Title</TextBlock>
        <TextBlock Style="{StaticResource Label}">Label</TextBlock>
        <TextBlock HorizontalAlignment="Right" FontSize="36" Foreground="{StaticResource MyBrush}" Text="Text" Margin="20" />
        <Button HorizontalAlignment="Left" Height="30" Background="{StaticResource MyBrush}" Margin="40">Button</Button>
        <Ellipse HorizontalAlignment="Center" Width="100" Height="100" Fill="{StaticResource MyBrush}" Margin="10" />
    </StackPanel>
</Border>

在上一個範例中,會 MyBrush 使用 StaticResource 標記延伸來 存取資源。 資源會指派給可接受所定義資源類型的屬性。 在此情況下, BackgroundForegroundFill 屬性。

資源字典中的所有資源都必須提供索引鍵。 不過,定義樣式時,可以省略索引鍵,如下一節 所述

如果您使用 StaticResource 標記延伸 從另一個資源內參考資源,則字典內找到的順序也會要求資源。 請確定您參考的任何資源都定義在集合中,早于要求該資源的位置。 如需詳細資訊,請參閱 靜態資源

如有必要,您可以使用 DynamicResource 標記延伸 在執行時間參考資源,以解決資源參考 的嚴格建立順序,但您應該注意這項技術 DynamicResource 有效能後果。 如需詳細資訊,請參閱 動態資源

樣式資源

下列範例會隱含且明確地參考樣式:

<Border>
    <StackPanel>
        <TextBlock Style="{StaticResource TitleText}">Title</TextBlock>
        <TextBlock Style="{StaticResource Label}">Label</TextBlock>
        <TextBlock HorizontalAlignment="Right" FontSize="36" Foreground="{StaticResource MyBrush}" Text="Text" Margin="20" />
        <Button HorizontalAlignment="Left" Height="30" Background="{StaticResource MyBrush}" Margin="40">Button</Button>
        <Ellipse HorizontalAlignment="Center" Width="100" Height="100" Fill="{StaticResource MyBrush}" Margin="10" />
    </StackPanel>
</Border>

在上述程式碼範例中 Style ,資源和 TitleTextLabel ,每個都會以特定控制項類型為目標。 在此情況下,兩者都會以 為目標 TextBlock 。 當屬性的資源索引鍵 Style 參考該樣式資源時,樣式會在目標控制項上設定各種不同的屬性。

雖然以 控制項為目標的 Border 樣式並未定義索引鍵。 省略索引鍵時,屬性的目標 TargetType 物件類型會隱含地當做樣式的索引鍵使用。 當樣式索引鍵設為類型時,只要這些控制項位於樣式範圍內,它就會成為該類型所有控制項的預設樣式。 如需詳細資訊,請參閱 Styles、DataTemplates 和隱含索引鍵

程式碼範例

下列程式碼片段示範如何透過程式碼建立和設定資源

建立樣式資源

建立資源並將它指派給資源字典時,隨時都可能發生。 不過,只有使用 DynamicResource 語法的 XAML 元素會在建立資源之後自動更新。

以下列視窗為例。 它有四個按鈕。 第四個 按鈕會使用 DynamicResource 來設定本身的樣式。 不過,此資源尚不存在,因此看起來就像是一般按鈕:

<StackPanel Margin="5">
    <Button Click="Button_Click">Explicitly Styled</Button>
    <Button>Unstyled</Button>
    <Button>Unstyled</Button>
    <Button Style="{DynamicResource ResourceKey=buttonStyle1}">Dynamically Styled</Button>
</StackPanel>

A window before a style is applied to a button

按一下第一個按鈕並執行下列工作時,會叫用下列程式碼:

  • 建立一些色彩以方便參考。
  • 建立新的樣式。
  • 將 setter 指派給樣式。
  • 將樣式新增為名為 buttonStyle1 的資源至視窗的資源字典。
  • 將樣式直接指派給引發 Click 事件的按鈕。
private void Button_Click(object sender, RoutedEventArgs e)
{
    // Create colors
    Color purple = (Color)ColorConverter.ConvertFromString("#4E1A3D");
    Color white = Colors.White;
    Color salmon = Colors.Salmon;

    // Create a new style for a button
    var buttonStyle = new Style(typeof(Button));

    // Set the properties of the style
    buttonStyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(purple)));
    buttonStyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(white)));
    buttonStyle.Setters.Add(new Setter(Control.BorderBrushProperty, new LinearGradientBrush(purple, salmon, 45d)));
    buttonStyle.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(5)));

    // Set this style as a resource. Any DynamicResource tied to this key will be updated.
    this.Resources["buttonStyle1"] = buttonStyle;

    // Set this style directly to a button
    ((Button)sender).Style = buttonStyle;
}
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)

    'Create colors
    Dim purple = DirectCast(ColorConverter.ConvertFromString("#4E1A3D"), Color)
    Dim white = Colors.White
    Dim salmon = Colors.Salmon

    'Create a new style for a button
    Dim buttonStyle As New Style()

    'Set the properties of the style
    buttonStyle.Setters.Add(New Setter(Control.BackgroundProperty, New SolidColorBrush(purple)))
    buttonStyle.Setters.Add(New Setter(Control.ForegroundProperty, New SolidColorBrush(white)))
    buttonStyle.Setters.Add(New Setter(Control.BorderBrushProperty, New LinearGradientBrush(purple, salmon, 45D)))
    buttonStyle.Setters.Add(New Setter(Control.BorderThicknessProperty, New Thickness(5)))

    'Set this style as a resource. Any DynamicResource looking for this key will be updated.
    Me.Resources("buttonStyle1") = buttonStyle

    'Set this style directly to a button
    DirectCast(sender, Button).Style = buttonStyle

End Sub

執行程式碼之後,視窗會更新:

A window after a style is applied to a button

請注意,前一個按鈕的樣式已更新。 此樣式會自動套用,因為按鈕使用 DynamicResource 標記延伸 來參考尚未存在的樣式。 一旦建立樣式並新增至視窗的資源,它就會套用至按鈕。 如需詳細資訊,請參閱 動態資源

尋找資源

下列程式碼會周遊執行所在的 XAML 物件的邏輯樹狀結構,以尋找指定的資源。 資源可能定義在物件本身,它是父系,一路到根目錄,應用程式本身。 下列程式碼會從按鈕本身開始搜尋資源:

myButton.Style = myButton.TryFindResource("buttonStyle1") as Style;
myButton.Style = myButton.TryFindResource("buttonStyle1")

明確參考資源

當您有資源的參考時,可以藉由搜尋或建立資源,直接將它指派給屬性:

// Set this style as a resource. Any DynamicResource tied to this key will be updated.
this.Resources["buttonStyle1"] = buttonStyle;
'Set this style as a resource. Any DynamicResource looking for this key will be updated.
Me.Resources("buttonStyle1") = buttonStyle

另請參閱