菜单项图标仅出现在最后一项

4
我可以帮您进行翻译。以下是需要翻译的内容:

我有一个具有以下样式的菜单项:

<Style TargetType="MenuItem">
    <Setter Property="Template" Value="{StaticResource MenuItem}"/>
    <Setter Property="Icon">
        <Setter.Value>
            <TextBlock FontWeight="Bold">Ic</TextBlock>
        </Setter.Value>
    </Setter>
    <Setter Property="Header" Value="{Binding Name}"/>
    <Setter Property="ItemsSource" Value="{Binding SubItems}"/>
</Style>

NameSubItemsMenuItem类的属性。 菜单的ItemsSource属性绑定到一个类型为List<MenuItem>的对象。)
问题在于“图标”部分只出现在菜单的最后一项上:

enter image description here

此外,如果我点击展开“播放列表”项目,会发生以下情况: enter image description here 我最终想将每个项目绑定到自己的图标,但似乎也行不通。有什么想法导致这种错误行为以及如何修复它?
更新:我看到了这个:带有图标的菜单项样式只创建一个图标 但对我来说并没有起作用,因为a.x:Shared=false导致XamlParseException,b.如果我将其移出Style.Resources,它不会抛出异常,但根本不起作用。请注意,我确实需要将其放在Style内部,因为最终我希望将其绑定到我正在绑定MenuItem的类的属性上。

1
可能是MenuItem style with icon creates only one icon的重复问题。 - Bruno V
看过了,但对我没用。将x:Shared=false设置后出现了异常。当我将其移到样式之外的ResourceDictionary中时,它没有抛出异常,但也没有起作用。 - Shachar Har-Shuv
我有同样的问题。你解决了吗? - undefined
2个回答

4
不要共享 TextBlock。
 <TextBlock x:Key="tb"  x:Shared="false" FontWeight="Bold">Ic</TextBlock>


<Style  TargetType="{x:Type MenuItem}">
    ...             
   <Setter Property="Icon" Value="{StaticResource tb}"/>
</Style>

x:Shared 只适用于 ResourceDictionary 中的项,而这个 TextBlock 并不在其中。 - undefined

0
有一个变通方法,但它有点丑陋。我猜“Ic”只是一个占位符,但我的答案会让你明白如何在其他情况下做到这一点。
在我的例子中,{x:Null}是一个占位符,通常你会绑定到视图模型中的一个字段,并使用转换器从该字段的值构建一个Image实例。
<Style TargetType="MenuItem">
    <Setter Property="Template" Value="{StaticResource MenuItem}"/>
    <Setter Property="Icon" Value="{Binding Source={x:Null}, Converter={StaticResource TextBlockConverter}}" />
    <Setter Property="Header" Value="{Binding Name}"/>
    <Setter Property="ItemsSource" Value="{Binding SubItems}"/>
</Style>

public class TextBlockConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return new TextBlock()
        {
            Text = "Ic";
            FontWeight = Bold
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接