かずきのBlog@hatena

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

UWPのコンパイル時データバインディングでString.Formatを使う

使えます。

こんなコードビハインドを書いて…

using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace App5
{
    public sealed partial class MainPage : Page
    {
        public DateTime Now => DateTime.Now;

        public MainPage()
        {
            this.InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.Bindings.Update();
        }
    }
}

そして、XAMLでこんな感じで書けます。

<Page x:Class="App5.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:local="using:App5"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:System="using:System"
      mc:Ignorable="d">

    <StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock Text="{x:Bind System:String.Format('{0:yyyy/MM/dd HH:mm:ss.fff}', Now)}" />
        <Button Content="Update"
                Click="Button_Click" />
    </StackPanel>
</Page>

ただまぁ、何故かエディタ上はエラーになるのですが…。実行すると動きます。

f:id:okazuki:20161005000837p:plain

まぁ、毎回フォーマットを指定するのもだるいので、書式出力系共通関数みたいなのを用意しておいて

using System;

namespace App5
{
    public static class Utils
    {
        public static string Format(DateTime dateTime)
        {
            return dateTime.ToString("yyyy/MM/dd HH:mm:ss.fff");
        }
    }
}

こういう感じで使うのがいいでしょう。

<Page x:Class="App5.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:local="using:App5"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:System="using:System"
      mc:Ignorable="d">

    <StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock Text="{x:Bind local:Utils.Format(Now)}" />
        <Button Content="Update"
                Click="Button_Click" />
    </StackPanel>
</Page>

ちなみに、これでもデザイナは表示されますがエディタ上はエラーになります…。 ツール類しっかりしてくれ。