「東雲 忠太郎」の平凡な日常のできごと

「東雲 忠太郎」の平凡な日常のできごと

2024.03.13
XML
カテゴリ: C#.NET


C# WPF アプリケーションでリソースファイルにテンプレートを記述して読み込む方法を説明します。


まず、WPF のリソースファイルにテンプレートを定義します。これを行うには、`ResourceDictionary` を使用します。この例では、`Window.Resources` セクションにテンプレートを定義します。


```xml

<Window x:Class="WpfApp.ResourceDictionaryExample.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="MainWindow" Height="450" Width="800">

    <Window.Resources>

        <ResourceDictionary>

            <ControlTemplate x:Key="MyButtonTemplate" TargetType="Button">

                <Border Background="LightBlue" BorderBrush="Black" BorderThickness="1"

                        CornerRadius="5" Padding="5">

                    <TextBlock Text="{TemplateBinding Content}" Foreground="White"

                               HorizontalAlignment="Center" VerticalAlignment="Center"/>

                </Border>

            </ControlTemplate>

        </ResourceDictionary>

    </Window.Resources>


    <Grid>

        <Button Template="{StaticResource MyButtonTemplate}" Content="Click Me"/>

    </Grid>

</Window>

```


この例では、`ControlTemplate` を使用して `MyButtonTemplate` というキーでテンプレートを定義しています。このテンプレートは、`Button` コントロールの見た目を定義しています。


次に、このテンプレートを使用する `Button` を定義します。`Button` の `Template` プロパティに、定義したテンプレートを `StaticResource` を使って指定します。


このようにすることで、`Button` は定義したテンプレートのスタイルを適用し、表示される内容がテンプレートに従ってレンダリングされます。


この方法を使えば、様々なコントロールや要素に対してカスタムのテンプレートを定義して、リソースファイルから読み込むことができます。






お気に入りの記事を「いいね!」で応援しよう

Last updated  2024.03.13 05:37:47


【毎日開催】
15記事にいいね!で1ポイント
10秒滞在
いいね! -- / --
おめでとうございます!
ミッションを達成しました。
※「ポイントを獲得する」ボタンを押すと広告が表示されます。
x

© Rakuten Group, Inc.
Create a Mobile Website
スマートフォン版を閲覧 | PC版を閲覧
Share by: