かずきのBlog@hatena

すきな言語は C# + XAML の組み合わせ。Azure Functions も好き。最近は Go 言語勉強中。日本マイクロソフトで働いていますが、ここに書いていることは個人的なメモなので会社の公式見解ではありません。

Universal Windows Platform appのコンパイル時バインディングをResourceDictionaryで使う方法

色々癖のあるコンパイル時バインディングですが、ResourceDicitionaryでDataTemplateを定義するときはひと手間加えないといけません。

ひと手間とは、コードビハインドを準備するのです。

ResourceDictionaryにx:Class属性をつけてクラス名を追加します。

<ResourceDictionary
    x:Class="App35.Dictionary1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App35">
    <DataTemplate x:Key="PersonTemplate" x:DataType="local:Person">
        <RelativePanel>
            <Border x:Name="Border" Background="Black">
                <Image x:Name="Image" 
                       Source="{x:Bind Picture}" 
                       Width="100" 
                       Height="100" 
                       Stretch="UniformToFill" />
            </Border>
            <TextBlock x:Name="TextBlockName"
                       Text="{x:Bind Name}"
                       Style="{ThemeResource TitleTextBlockStyle}"
                       RelativePanel.RightOf="Border"
                       RelativePanel.AlignVerticalCenterWith="Border" />
        </RelativePanel>
    </DataTemplate>
</ResourceDictionary>

そして、その名前のクラスを準備してコンストラクタでInitializeComponentを呼び出します。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace App35
{
    public partial class Dictionary1
    {
        public Dictionary1()
        {
            InitializeComponent();
        }
    }
}

このResourceDictionaryを使うときは、クラス名で使用します。

<Application
    x:Class="App35.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App35"
    RequestedTheme="Light">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <!-- クラス名を使ってマージ -->
                <local:Dictionary1 />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>