WPF 리소스를 정의하고 참조하는 방법(WPF .NET)

이 예제에서는 리소스를 정의하고 참조하는 방법을 보여줍니다. 리소스는 XAML 또는 코드를 통해 참조할 수 있습니다.

중요

.NET 7 및 .NET 6에 관한 데스크톱 가이드 설명서는 제작 중입니다.

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>

이전 예제에서는 MyBrush 리소스는 StaticResource 태그 확장을 사용하여 액세스합니다. 리소스는 정의되는 리소스의 형식을 허용할 수 있는 속성에 할당됩니다. 이 경우 Background, ForegroundFill 속성입니다.

리소스 사전의 모든 리소스는 키를 제공해야 합니다. 하지만 스타일이 정의되면 다음 섹션에 설명된 대로 키를 생략할 수 있습니다.

또한 StaticResource 태그 확장을 사용하여 다른 리소스 내에서 리소스를 참조하는 경우 리소스는 사전 내에서 찾은 순서로 요청됩니다. 참조하는 모든 리소스가 해당 리소스가 요청된 위치보다 이전의 컬렉션에 정의되어 있는지 확인합니다. 자세한 내용은 정적 리소스를 참조하세요.

필요한 경우 DynamicResource 태그 확장을 사용하여 런타임에 리소스를 참조하면 리소스 참조의 엄격한 순서를 해결할 수 있지만 이 DynamicResource 기법은 성능에 영향이 있다는 점을 알아야 합니다. 자세한 내용은 Dynamic 리소스를 참조하세요.

스타일 리소스

다음 예제에서는 암시적 및 명시적으로 스타일을 참조합니다.

<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 속성의 대상이 되는 개체 형식이 스타일에 대한 키로 암시적으로 사용됩니다. 스타일이 형식에 키가 지정되면 해당 컨트롤이 스타일의 범위 내에 있는 한 해당 형식의 모든 컨트롤에 대한 기본 스타일이 됩니다. 자세한 내용은 스타일, DataTemplates 및 암시적 키를 참조하세요.

코드 예제

다음 코드 조각은 코드를 통해 리소스를 만들고 설정하는 것을 보여줍니다.

스타일 리소스 만들기

리소스를 만들고 리소스 사전에 할당하는 작업은 언제든지 발생할 수 있습니다. 단, DynamicResource 구문을 사용하는 XAML 요소만 리소스가 생성된 후 자동으로 업데이트됩니다.

예를 들어, 다음 창을 살펴보겠습니다. 4개의 단추가 있습니다. 네 번째 단추는 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 태그 확장을 사용하여 아직 존재하지 않는 스타일을 참조했기 때문에 스타일이 자동으로 적용되었습니다. 스타일이 만들어지고 창의 리소스에 추가되면 단추에 적용되었습니다. 자세한 내용은 Dynamic 리소스를 참조하세요.

리소스 찾기

다음 코드는 실행되는 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

참고 항목