Neutral Scent

App developments & Gadgets

選択可能なTextBlock風TextBoxを作る


HTMLと違ってSilverlightは通常のテキストは選択できませんが、Silverlightでも表示しているテキストを選択可能にしておきたいこともあります。
WinRTではTexBlockやRichTextBlockにIsTextSelectionEnabledというそのものずばりなプロパティがあるのですが、軽量フレームワークSilverlightにそんな便利なモノはありません。
なのでReadOnlyにしたTextBoxのスタイルで余計な装飾を削り取ってそれっぽく見せるわけです。
まずは、リソースにスタイルを定義、頻繁に使うのであればApp.xamlにでも放り込みましょう。

<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.Resources>
        <Style x:Key="ReadOnlyTextBox" TargetType="TextBox">
            <Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}" />
            <Setter Property="IsReadOnly" Value="True" />
            <Setter Property="TextWrapping" Value="Wrap" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate>
                        <Grid>
                            <ContentPresenter x:Name="ContentElement" />
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Grid.Resources>
    ...

しかる後に、スタイルとしてリソースを参照するだけです。

<TextBox Text="This is test." Style="{StaticResource ReadOnlyTextBox}"/>

Windows Phoneのテキスト選択は正直微妙にやりにくいので、タップしたら全選択するようにしておくと気が利いているかもしれませんね。

<TextBox Text="This is test." Style="{StaticResource ReadOnlyTextBox}" Tap="TextBox_Tap_1"/>
private void TextBox_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
{
    var textbox = sender as TextBox;
    textbox.Select(0, textbox.Text.Length);
}

via: SharpGIS | Windows Phone 7 Copy/Paste on TextBlocks
http://www.sharpgis.net/post/2011/04/03/Windows-Phone-7-CopyPaste-on-TextBlocks.aspx