Visual Studio/WPF > Resources > 구현 > 버튼을 누르면 색상 변경 > FindResource() 사용 | TryFindResource()

운영 환경
Windows 7 Pro (32bit)
Microsoft Visual Studio 2017 Community

링크



XAML Resources
Resources and Code

구현



Resource를 정의하고 버튼을 누를 때 Style을 할당하는 구현을 해 보았다.

MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace _170614_t1939_resourceStyle
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void GoodButton_Click(object sender, RoutedEventArgs e)
        {
            uxTitle.Style = this.FindResource("TitleText") as Style;
        }
    }
}

MainWindow.xaml
<Window x:Class="_170614_t1939_resourceStyle.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:_170614_t1939_resourceStyle"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Style TargetType="TextBlock" x:Key="TitleText">
            <Setter Property="Background" Value="LightGreen"/>
            <Setter Property="FontSize" Value="18"/>
            <Setter Property="Foreground" Value="White"/>
            <Setter Property="FontFamily" Value="Trebuchet MS"/>
        </Style>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="10*"/>
            <RowDefinition Height="28*"/>
            <RowDefinition Height="8*"/>
            <RowDefinition Height="89*"/>
        </Grid.RowDefinitions>
        <TextBlock TextWrapping="Wrap" 
                   Text="Kiita"/>
        <TextBlock Grid.Row="1" TextWrapping="Wrap" Height="Auto"
                   x:Name="uxTitle"
                   Text="Visual Studio / WPF > link > XAML Resources"/>
        <Button Content="Good!" 
                x:Name="GoodButton"
                Click="GoodButton_Click"
                HorizontalAlignment="Left" Margin="419,32,0,0" Grid.Row="1" VerticalAlignment="Top" Width="75"/>
    </Grid>
</Window>

실행 예



버튼 누르기 전


버튼을 누른 후


링크



다음 링크는 향후 도움이 될 수 있습니다.

ViewModel에서 Style을 지정하는 방법. StyleConverter로 FindResource 오염 방지

TryFindResource



Resources and Code

FindResource raises an exception; TryFindResource will not raise an exception but returns null.

좋은 웹페이지 즐겨찾기