1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【WPF】TextBoxからTextBlockに変更する際の注意事項 ※スクロールバーなど

Last updated at Posted at 2025-02-27

はじめに

数年前に開発したデスクトップ版アドインを最近一部改修したので、
備忘録として記載いたします。

背景

メッセージ表示で使用しているコンポーネントをCSSのように装飾したい
例:「こんな風に特定の文字列のフォントを変更したい要望でした」

課題と対応策

課題1

使用しているコントロールが TextBox のため、特定の文字列のみの装飾に対応していない。
TextBlock に変更する

課題2

TextBlock が VerticalScrollBarVisibility プロパティや BorderBrush プロパティに対応していない。
⇒ 個別にスクロールバー、ボーダーを配置する(これが大変でした)

実装

改修前

改修前の TextBox の中身がこんな感じです。
コントロールのプロパティでレイアウトを一括で設定しています。

<Grid.ColumnDefinitions>
    <ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
    <RowDefinition Height="*" />
    <RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBox  Height="70" FontSize="12" Name="MessageLabel" Foreground="Red" 
    FontWeight="Bold" Text="" VerticalScrollBarVisibility="Visible" IsReadOnly="True" 
    TextWrapping="Wrap" BorderBrush="#FFD5DFE5" Grid.Column="0" Grid.Row="0" />

改修後

次に改修後の TextBlock の中身がこんな感じです。
課題2で記載した TextBlock で用意されていないプロパティについては個別にコントロールを配置しました。

ただしスクロールバーを配置する際は、
Gridの高さを Height="*" ではなく、数値で指定するようにしてください。
理由はおそらく以下の記事に書いてある通りかと思いますが、スクロールのノブが表示されなくなります。

<Grid.ColumnDefinitions>
    <ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
    <RowDefinition Height="75" />
    <RowDefinition Height="*" />
</Grid.RowDefinitions>
<Border BorderBrush="#FFD5DFE5" BorderThickness="1">
    <ScrollViewer>
        <TextBlock FontSize="12" Name="MessageLabel" Foreground="Red" 
            FontWeight="Bold" TextWrapping="Wrap" Grid.Column="0" Grid.Row="0">
        </TextBlock>
    </ScrollViewer>
</Border>

また上のコードでは文字の装飾を赤文字・太字で設定していますが、
通常の黒文字で表示したい文字列についてはxaml.cs側で以下のように対応してください。

MessageLabel.Inlines.Clear();
MessageLabel.Inlines.Add(new Run() { Text = "これは黒文字", FontWeight = FontWeights.Normal, Foreground = Brushes.Black });
MessageLabel.Inlines.Add(new Run() { Text = "これは赤文字・太字" });            
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?