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

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

XAML 範例

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

<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>

資源

SolidColorBrush 資源 MyBrush 可用來提供數個屬性的值,每個屬性都會採用 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>

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

套用樣式至按鈕之前的視窗

點擊第一個按鈕時將呼叫以下程式碼並執行以下工作:

  • 建立一些色彩以方便參考。
  • 建立新的樣式。
  • 將 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

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

套用樣式至按鈕後的視窗

請注意,前一個按鈕的樣式已更新。 此樣式會自動套用,因為按鈕使用 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

另請參閱