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

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

2024.04.21
XML
カテゴリ: C#.NET


WPFでコントロールテンプレートを別ファイルに定義するには、リソースディクショナリを使用してテンプレートを定義し、必要な箇所でそれを参照する方法があります。以下に、コントロールテンプレートを別ファイルに定義するサンプルを示します。


まず、テンプレートを定義するXAMLファイル(例: ButtonTemplate.xaml)を作成します。


```xml

<!-- ButtonTemplate.xaml -->


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

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


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

        <Border Background="LightGray" BorderBrush="Black" BorderThickness="1">

            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>

        </Border>

    </ControlTemplate>


</ResourceDictionary>

```


次に、アプリケーションのリソースにこのテンプレートファイルを追加します。これにより、アプリケーション内のどこからでもこのテンプレートを参照できるようになります。


```xml

<!-- App.xaml -->


<Application x:Class="WpfApp.App"

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

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

    <Application.Resources>

        <ResourceDictionary>

            <ResourceDictionary.MergedDictionaries>

                <ResourceDictionary Source="ButtonTemplate.xaml"/>

            </ResourceDictionary.MergedDictionaries>

        </ResourceDictionary>

    </Application.Resources>

</Application>

```


最後に、テンプレートを使用するXAMLファイルでそのテンプレートを参照します。


```xml

<!-- MainWindow.xaml -->


<Window x:Class="WpfApp.MainWindow"

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

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

    <Grid>

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

    </Grid>

</Window>

```


このようにすることで、Buttonのテンプレートが別ファイルに定義され、MainWindow.xamlでそのテンプレートを参照しています。これにより、テンプレートの再利用性が向上し、プロジェクト内でコードの重複を減らすことができます。






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

Last updated  2024.04.21 15:25:56


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

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