Generic.xamlを見やすく管理する(C# WPF)

C#

カスタムコントロールの追加をします。
そうすると、下記のようなThemesフォルダとGeneric.xamlが出現します。
これ以外にもhogehoge.csも追加されます。

Generic.xaml とは特別なResourceDictionaryです。
Generic.xamlにすべてのカスタムコントロールを定義します。

Generic.xaml

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApp3">

    <Style TargetType="{x:Type local:ImageButton}">
        <Setter Property="Height" Value="{Binding Path=Height, RelativeSource={RelativeSource TemplatedParent}}"/>
        <Setter Property="Width" Value="{Binding Path=Width, RelativeSource={RelativeSource TemplatedParent}}"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:ImageButton}">
                    <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">
                            <TextBlock Text="{TemplateBinding Content}" Background="Brown"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

1例を挙げるとこんな感じで定義します。
上記ではImageButton Classを定義してみました。

これはGeneric.xaml内にあるImageButtonのデザインとImageButton.csが散らばって、非常に探しにくくなります。
強引な手法になりますが、UserControlのようにxaml/xaml.csがネストされている方が管理しやすいので、適当なUserControlを追加して、中身をそれぞれ置き換えます。

そして、Generic.xamlからStyleを削除したので、新たに作成したXamlへの参照を渡します。

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApp3">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/WpfApp3;component/ImageButton.xaml"/>
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

これで表示もスッキリです。

このCustom Controlは適当なCustom Controlフォルダでも作って固めてれば尚よいです。

C#
スポンサーリンク
Once and Only

コメント