Shachar Har-Shuv
Shachar Har-Shuv

Reputation: 822

MenuItem.Icon appears only on the last item

I have a Menu with the following style on the items:

<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>

(Name, and SubItems are properties of the class MenuItem. the ItemsSource property of the menu is bound to an object of type List<MenuItem> )

problem is the "Icon" part appears only on the last item of the menu:

enter image description here

Furthermore, if I click to expand the "Playlist" Item here's what happens: enter image description here

I ultimately want to bind each Item to its own Icon, but that doesn't seem to work either. Any ideas what causes this misbehavior and how to fix it?

update I've seen this: MenuItem style with icon creates only one icon but it didn't work for me because a. x:Shared=false made a XamlParseException and b. if I moved it out of the Style.Resources it didn't make an exception but simply didn't work. Note that I do need this INSIDE the Style because ultimately I want it to be bound to a property of the class I'm binding the MenuItem to.

Upvotes: 5

Views: 868

Answers (2)

Spook
Spook

Reputation: 25927

There is a workaround, but its kind of ugly. I guess the "Ic" is only a placeholder, but my answer will get you the idea how to do that in other cases.

In my example {x:Null} is a placeholder, normally you'd bind to a field in your viewmodel and use converter to build an Image instance from that field's value.

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

Upvotes: 0

Bob Ding
Bob Ding

Reputation: 59

Don't Share the TextBlock

 <TextBlock x:Key="tb"  x:Shared="false" FontWeight="Bold">Ic</TextBlock>


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

Upvotes: 4

Related Questions