Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何格式化WPF菜单项中的文本?_C#_Wpf - Fatal编程技术网

C# 如何格式化WPF菜单项中的文本?

C# 如何格式化WPF菜单项中的文本?,c#,wpf,C#,Wpf,我有这样一个菜单项: menu.Items.Insert(0, new MenuItem { Header = String.Format("Foo \"{0}\" bar", "qux") }); 我的问题是:如何在{0}部分应用一些文本格式,如前景颜色?您可以使用具有不同格式的内联元素的文本块: TextBlock text = new TextBlock(); text.Inlines.AddRange( new Inline[] {

我有这样一个菜单项:

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

我的问题是:如何在
{0}
部分应用一些文本格式,如
前景
颜色?

您可以使用具有不同格式的
内联
元素的
文本块

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

您可以将
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
}); 

标题
属性是MenuItem的内容元素,类型为
对象

考虑如何使用Xaml设置菜单项的格式,例如:

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

福
... 等

在代码中模拟它

标题属性是菜单项的内容元素,类型为
对象

考虑如何使用Xaml设置菜单项的格式,例如:

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

福
... 等
在代码中模拟它

控件模板控件模板