2012-06-02 28 views
1

我有這樣一個菜單項:如何格式化WPF菜單項中的文本?

menu.Items.Insert(0, new MenuItem 
{ 
    Header = String.Format("Foo \"{0}\" bar", "qux") 
}); 

我的問題是:我怎麼能應用一些文本格式的東西像Foreground顏色的{0}一部分?

+0

控件模板http://msdn.microsoft.com/en-us/library/ms747082(v=vs.85).aspx – kenny

回答

1

您可以使用一個TextBlock用不同格式Inline元素:

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 
}); 
0

Header屬性是菜單項內容元素,是object型。

考慮一下如何去格式化使用XAML菜單項,一個例子是:

<MenuItem> 
    <MenuItem.Header> 
     <TextBlock> 
      <Run Background="Yellow" Foreground="Red" FontWeight="Bold"> 
       Foo 
      </Run> 
      ... etc 
     </TextBlock> 
    </MenuItem.Header> 
</MenuItem> 

效仿,在代碼。