次のようなメニュー項目があります。
menu.Items.Insert(0, new MenuItem
{
Header = String.Format("Foo \"{0}\" bar", "qux")
});
私の質問は次のとおりです。Foreground
色などのテキスト書式設定を{0}
パーツに適用するにはどうすればよいですか?
TextBlock
異なる形式Inline
の要素でa を使用できます。
TextBlock text = new TextBlock();
text.Inlines.AddRange(
new Inline[]
{
new Run("Foo "),
new Run(string.Format("\"{0}\"", "qux")) {Foreground = Brushes.Red},
new Run(" bar")
});
menu.Items.Insert(0, new MenuItem
{
Header = text
});
このHeader
プロパティは、MenuItem のコンテンツ要素であり、タイプは ですobject
。
Xaml を使用してメニュー項目をフォーマットする方法を考えてみましょう。1 つの例は次のようになります。
<MenuItem>
<MenuItem.Header>
<TextBlock>
<Run Background="Yellow" Foreground="Red" FontWeight="Bold">
Foo
</Run>
... etc
</TextBlock>
</MenuItem.Header>
</MenuItem>
それをコードでエミュレートします。