長文を設定したTextBlockに省略表示させる (2)

2025年4月19日土曜日

C# WPF カスタムコントロール

記事のカテゴリー: C#、.NET9、WPF

長文を設定したTextBlockに初期では省略表示させ、必要なら全文表示に切り替えることのできるカスタムコントロールを考えます。ちなみに、ChatGPTに協力してもらいました。以前作ったもの(長文を設定したTextBlockに省略表示させる)と別バージョンです。

以前作ったものとの違い

以前にも同じ趣旨のカスタムコントロールを作っています(長文を設定したTextBlockに省略表示させるを参照してください)。以前作ったものはTextBlockの文章を右端で折り返さない前提でした。今回は逆に文章を折り返す前提のものになります。

実装

文章に加えて現在の状態(省略表示しているか、全文表示しているか)を示す部品を配置したかったので、Controlを継承したクラスを作成して内部にTextBlockを持つ形になりました。外観(XAMLで書いたスタイル)とコードビハインド(C#のコード)の二部構成になります。

このような構成やコントロールの名前はChatGPTの提案が色濃い部分です。

外観

Fluentデザインになじむような外観になっています(なっているつもり)。PART_TextBlockが内部のTextBlockChevronIconが現在の表示の状態を表す矢印アイコンです。矢印アイコンは実際にはアイコンフォントを使ったTextBlockになっています。

このスタイルはアプリケーションのリソース(AppクラスのResourcesプロパティなど)に書いてください。

XAML:

  1. <Style x:Key="ChevronTextBlockStyle" TargetType="TextBlock">
  2. <Setter Property="FontFamily" Value="Segoe Fluent Icons, Segoe MDL2 Assets" />
  3. <Setter Property="FontSize" Value="11" />
  4. </Style>
  5. <Style TargetType="{x:Type local:ExpandableTextBlock}">
  6. <Setter Property="ToolTipService.InitialShowDelay" Value="100" />
  7. <Setter Property="ToolTipService.Placement" Value="Relative" />
  8. <Setter Property="Template">
  9. <Setter.Value>
  10. <ControlTemplate TargetType="{x:Type local:ExpandableTextBlock}">
  11. <Border
  12. x:Name="Border"
  13. Background="{TemplateBinding Background}"
  14. BorderBrush="{TemplateBinding BorderBrush}"
  15. BorderThickness="{TemplateBinding BorderThickness}"
  16. CornerRadius="{TemplateBinding Border.CornerRadius}"
  17. ToolTip="{TemplateBinding ToolTip}"
  18. ToolTipService.InitialShowDelay="{TemplateBinding ToolTipService.InitialShowDelay}"
  19. ToolTipService.Placement="{TemplateBinding ToolTipService.Placement}">
  20. <Grid>
  21. <Grid.ColumnDefinitions>
  22. <ColumnDefinition Width="*" />
  23. <ColumnDefinition Width="Auto" />
  24. </Grid.ColumnDefinitions>
  25. <!-- 内部の TextBlock -->
  26. <TextBlock
  27. x:Name="PART_TextBlock"
  28. Grid.Column="0"
  29. Padding="{TemplateBinding Padding}"
  30. VerticalAlignment="Top"
  31. FontFamily="{TemplateBinding FontFamily}"
  32. FontSize="{TemplateBinding FontSize}"
  33. FontStretch="{TemplateBinding FontStretch}"
  34. FontStyle="{TemplateBinding FontStyle}"
  35. FontWeight="{TemplateBinding FontWeight}"
  36. Foreground="{TemplateBinding Foreground}"
  37. Text="{TemplateBinding Text}"
  38. TextTrimming="CharacterEllipsis"
  39. TextWrapping="Wrap"
  40. ToolTipService.InitialShowDelay="100"
  41. ToolTipService.Placement="Relative" />
  42. <!-- 右上の矢印アイコン -->
  43. <TextBlock
  44. x:Name="ChevronIcon"
  45. Grid.Column="1"
  46. Margin="4,4,4,0"
  47. VerticalAlignment="Top"
  48. Style="{StaticResource ChevronTextBlockStyle}"
  49. Text="&#xE70D;"
  50. Visibility="{TemplateBinding ChevronIconVisibility}" />
  51. </Grid>
  52. </Border>
  53. <ControlTemplate.Triggers>
  54. <!-- 表示が切り替わったら矢印アイコンの向きを逆にする -->
  55. <Trigger Property="IsExpanded" Value="True">
  56. <Setter TargetName="ChevronIcon" Property="Text" Value="&#xE70E;" />
  57. </Trigger>
  58. <!-- 省略表示中はツールチップに全文を設定する -->
  59. <MultiTrigger>
  60. <MultiTrigger.Conditions>
  61. <Condition Property="AutoTooltip" Value="True" />
  62. <Condition Property="ChevronIconVisibility" Value="Visible" />
  63. <Condition Property="IsExpanded" Value="False" />
  64. </MultiTrigger.Conditions>
  65. <Setter TargetName="Border" Property="ToolTip" Value="{Binding Text, RelativeSource={RelativeSource TemplatedParent}}" />
  66. </MultiTrigger>
  67. </ControlTemplate.Triggers>
  68. </ControlTemplate>
  69. </Setter.Value>
  70. </Setter>
  71. </Style>

コードビハインド

コードビハインドでは文章の高さや行の高さを計算して、内部のTextBlockや矢印アイコンの表示を制御します。TextBlockに短縮表示させる方法については、MaxHeightプロパティに最大行数分の高さを指定して超過分を表示させないようにしています。

C#:

  1. public class ExpandableTextBlock : Control
  2. {
  3. static ExpandableTextBlock()
  4. {
  5. DefaultStyleKeyProperty.OverrideMetadata(typeof(ExpandableTextBlock), new FrameworkPropertyMetadata(typeof(ExpandableTextBlock)));
  6. }
  7.  
  8. public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
  9. "Text", typeof(string), typeof(ExpandableTextBlock), new FrameworkPropertyMetadata(string.Empty, OnPropertyChanged));
  10.  
  11. // 最大行数のプロパティ
  12. public static readonly DependencyProperty MaxLinesProperty = DependencyProperty.Register(
  13. "MaxLines", typeof(int), typeof(ExpandableTextBlock), new FrameworkPropertyMetadata(3, OnPropertyChanged));
  14. // 全体表示しているかどうかを表すプロパティ
  15. public static readonly DependencyProperty IsExpandedProperty = DependencyProperty.Register(
  16. "IsExpanded", typeof(bool), typeof(ExpandableTextBlock), new FrameworkPropertyMetadata(false, OnPropertyChanged));
  17.  
  18. private static readonly DependencyPropertyKey ChevronIconVisibilityPropertyKey = DependencyProperty.RegisterReadOnly(
  19. "ChevronIconVisibility", typeof(Visibility), typeof(ExpandableTextBlock), new FrameworkPropertyMetadata(Visibility.Collapsed));
  20.  
  21. // そもそも省略表示が必要かどうかを表すプロパティ
  22. public static readonly DependencyProperty ChevronIconVisibilityProperty = ChevronIconVisibilityPropertyKey.DependencyProperty;
  23.  
  24. // 省略表示中にツールチップに全文を設定するかどうかを表すプロパティ
  25. public static readonly DependencyProperty AutoTooltipProperty = DependencyProperty.Register(
  26. "AutoTooltip", typeof(bool), typeof(ExpandableTextBlock), new FrameworkPropertyMetadata(false));
  27.  
  28. private TextBlock? textBlock;
  29.  
  30. public string Text
  31. {
  32. get { return (string)GetValue(TextProperty); }
  33. set { SetValue(TextProperty, value); }
  34. }
  35.  
  36. public int MaxLines
  37. {
  38. get { return (int)GetValue(MaxLinesProperty); }
  39. set { SetValue(MaxLinesProperty, value); }
  40. }
  41.  
  42. public bool IsExpanded
  43. {
  44. get { return (bool)GetValue(IsExpandedProperty); }
  45. set { SetValue(IsExpandedProperty, value); }
  46. }
  47.  
  48. public Visibility ChevronIconVisibility
  49. {
  50. get { return (Visibility)GetValue(ChevronIconVisibilityProperty); }
  51. private set { SetValue(ChevronIconVisibilityPropertyKey, value); }
  52. }
  53.  
  54. public bool AutoTooltip
  55. {
  56. get { return (bool)GetValue(AutoTooltipProperty); }
  57. set { SetValue(AutoTooltipProperty, value); }
  58. }
  59.  
  60. private static void OnPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
  61. {
  62. if (obj is not ExpandableTextBlock control)
  63. {
  64. return;
  65. }
  66.  
  67. control.UpdateDisplay();
  68. }
  69.  
  70. public override void OnApplyTemplate()
  71. {
  72. base.OnApplyTemplate();
  73. textBlock = GetTemplateChild("PART_TextBlock") as TextBlock;
  74.  
  75. if (textBlock != null)
  76. {
  77. textBlock.Loaded += TextBlock_Loaded;
  78. textBlock.SizeChanged += TextBlock_SizeChanged;
  79. }
  80. }
  81.  
  82. // コントロールがクリックされると省略表示と全文表示を切り替える
  83. protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
  84. {
  85. if (ChevronIconVisibility == Visibility.Visible)
  86. {
  87. IsExpanded = !IsExpanded;
  88. }
  89.  
  90. base.OnMouseLeftButtonDown(e);
  91. }
  92.  
  93. private void TextBlock_Loaded(object sender, RoutedEventArgs e)
  94. {
  95. UpdateDisplay();
  96. }
  97.  
  98. private void TextBlock_SizeChanged(object sender, SizeChangedEventArgs e)
  99. {
  100. if (e.WidthChanged)
  101. {
  102. UpdateDisplay();
  103. }
  104. }
  105.  
  106. // 文章の「高さ」を計算して、ChevronIconVisibility と内部 TextBlock の MaxHeight に反映する
  107. private void UpdateDisplay()
  108. {
  109. double GetHeight(TextBlock textBlock)
  110. {
  111. return new FormattedText(
  112. Text ?? string.Empty,
  113. CultureInfo.CurrentCulture,
  114. FlowDirection.LeftToRight,
  115. new Typeface(textBlock.FontFamily, textBlock.FontStyle, textBlock.FontWeight, textBlock.FontStretch),
  116. textBlock.FontSize,
  117. textBlock.Foreground,
  118. VisualTreeHelper.GetDpi(textBlock).PixelsPerDip
  119. )
  120. {
  121. MaxTextWidth = textBlock.ActualWidth,
  122. }.Height;
  123. }
  124.  
  125. if ((textBlock == null) || (textBlock.ActualWidth == 0))
  126. {
  127. if (textBlock != null)
  128. {
  129. textBlock.MaxHeight = double.PositiveInfinity;
  130. }
  131.  
  132. return;
  133. }
  134.  
  135. double lineHeight = !double.IsNaN(textBlock.LineHeight) ? textBlock.LineHeight : textBlock.FontSize * textBlock.FontFamily.LineSpacing;
  136. ChevronIconVisibility = (GetHeight(textBlock) > lineHeight * MaxLines) ? Visibility.Visible : Visibility.Collapsed;
  137. textBlock.MaxHeight = ((ChevronIconVisibility != Visibility.Visible) || IsExpanded) ? double.PositiveInfinity : MaxLines * lineHeight;
  138. }
  139. }

使用例

XAML:

  1. <local:ExpandableTextBlock
  2. AutoTooltip="True"
  3. MaxLines="3"
  4. Text="長い文章" />