问题
I have the following XAML to provide a recent document menu like VS2012's FILE > Recent Documents menu
<MenuItem Header="_FILE">
...
<MenuItem Header="_Recent Studies"
ItemsSource="{Binding RecentFiles}"
AlternationCount="{Binding RecentFiles.Count}"
HeaderTemplate="{x:Null}">
<MenuItem.Resources>
<Style TargetType="{x:Type MenuItem}"
BasedOn="{StaticResource {x:Type MenuItem}}">
<Setter Property="HeaderTemplate" >
<Setter.Value>
<DataTemplate>
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0}. {1}">
<Binding Path="(ItemsControl.AlternationIndex)"
RelativeSource="{RelativeSource FindAncestor,
AncestorType={x:Type MenuItem}}"/>
<Binding Path="FullFileName"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</MenuItem.Resources>
</MenuItem>
<Separator/>
<MenuItem Header="E_xit"
Height="22"
Icon="{Binding Source={StaticResource Close},
Converter={StaticResource drawingBrushToImageConverter}}"
Command="{Binding ExitCommand}" />
</MenuItem>
This works! However, all my XAML for the FILE MenuItem
block is being highlighted and I get a compile-time error (the code runs and works though!), saying
An object of the type "System.Windows.StaticResourceExtension" cannot be applied to a property that expects the type "System.Windows.Style".
I am using .NET4.5 and VS2012. Why is this happening and how can I resolve it?
Thanks for your time.
回答1:
Try something like this
You should be able to move the Style
to any ResourceDictionary
and it should still work, you will just have to apply it to the Items inside the MenuItem
using ItemContainerStyle
<Window.Resources>
<Style x:Key="MyMenuStyle" TargetType="{x:Type MenuItem}" >
<Setter Property="HeaderTemplate" >
<Setter.Value>
<DataTemplate>
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0}. {1}">
<Binding Path="(ItemsControl.AlternationIndex)" RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type MenuItem}}"/>
<Binding Path="FullFileName"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Menu VerticalAlignment="Top">
<MenuItem Header="_FILE" >
<MenuItem Header="_Recent Studies"
ItemsSource="{Binding RecentFiles}"
AlternationCount="{Binding RecentFiles.Count}"
ItemContainerStyle="{StaticResource MyMenuStyle}" />
<Separator/>
<MenuItem Header="E_xit" Height="22" Command="{Binding ExitCommand}" />
</MenuItem>
</Menu>
</Grid>
来源:https://stackoverflow.com/questions/18846661/odd-xaml-error-system-windows-staticresourceextension-cannot-be-applied