かずきのBlog@hatena

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

UWPでTextBlock内にリンクを仕込む

TextBlockはTextプロパティに文字列を指定する以外に、InlinesにRun(テキスト)やHyperlink(名前の通りリンク)を埋め込んで、単純なテキスト以上の表示をすることが出来るようになっています。

例えば以下のようなXAMLを定義して

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

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock x:Name="TextBlock" />
    </Grid>
</Page>

以下のようなコードビハインドで

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

// 空白ページのアイテム テンプレートについては、http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 を参照してください

namespace App36
{
    /// <summary>
    /// それ自体で使用できる空白ページまたはフレーム内に移動できる空白ページ。
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();

            // TextBlockのInlinesプロパティにRunとHyperlinkを入れ込む
            this.TextBlock.Inlines.Add(new Run
            {
                Text = "Hello",
                Foreground = new SolidColorBrush(Colors.Red)
            });

            var link = new Hyperlink
            {
                NavigateUri = new Uri("http://blog.okazuki.jp")
            };
            link.Inlines.Add(new Run
            {
                Text = "World"
            });
            this.TextBlock.Inlines.Add(link);
        }
    }
}

こんな表示になります。

f:id:okazuki:20160225231848p:plain

因みにInlinesプロパティはコンテンツプロパティでもあるので、TextBlock直下にRunとかを定義できます。上記コードと同じことをXAMLでやる場合は以下のようになります。

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

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock x:Name="TextBlock">
            <Run Text="Hello"
                 Foreground="Red" />
            <Hyperlink NavigateUri="http://blog.okazuki.jp">World</Hyperlink>
        </TextBlock>
    </Grid>
</Page>