MVVMを使用してWPF/XAMLアプリで作業しており、ビューモデルのプロパティとして文字列のコレクションがあります。テキストブロックまたは同様のコントロール内に表示するために文字列を連結したいと思います。文字列はテキスト「AND」を使用して連結する必要があり、連結テキストは太字のフォントの太さを使用してスタイル設定する必要があります。出力は次のようになります。
猫と犬とマウスとウサギ
私の最終結果を達成するための最良の方法は何ですか?
読み取り専用のTextBlock.Inlinesプロパティにバインドすることはできないため、次のプロパティを使用して派生TextBlockを作成することをお勧めしTextList
ます。
public class TextListBlock : TextBlock
{
public static readonly DependencyProperty TextListProperty = DependencyProperty.Register(
"TextList", typeof(IEnumerable<string>), typeof(TextListBlock),
new PropertyMetadata((o, e) => ((TextListBlock)o).TextListChanged((IEnumerable<string>)e.NewValue)));
public IEnumerable<string> TextList
{
get { return (IEnumerable<string>)GetValue(TextListProperty); }
set { SetValue(TextListProperty, value); }
}
private void TextListChanged(IEnumerable<string> textList)
{
bool addSeparator = false;
foreach (string text in textList)
{
if (addSeparator)
{
Inlines.Add(new Run(" AND ") { FontWeight = FontWeights.Bold });
}
Inlines.Add(new Run(text));
addSeparator = true;
}
}
}
コレクション内の各アイテム (この例では動物) の ViewModel を作成することになりました。これを行う際に、IsNotLast というプロパティを追加しました。これは、アイテム間に「AND」テキストを表示するタイミングを決定するのに役立ちます。さらに、BooleanToVisibilityConverterを使用して、XAML の可視性プロパティが適切に設定されるようにしました。
以下は、ItemsControl と DataTemplate を使用した XAML の例です。
<ItemsControl ItemsSource="{Binding Path=Animals}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock
Text="{Binding AnimalName}"
/>
<TextBlock
Text=" AND "
FontWeight="Bold"
Visibility="{Binding IsNotLast, Converter={StaticResource booleanToVisibilityConverter}}"
/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>