问题
Hi I am trying to have a MenuItem.Icon set thru a style setter:
<Style x:Key="MenuItem_Delete" TargetType="MenuItem"
BasedOn="{StaticResource {x:Type MenuItem}}">
<Setter Property="Header" Value="_Delete"/>
<Setter Property="MenuItem.Icon">
<Setter.Value>
<Image Source="Resources/Delete.png"/>
</Setter.Value>
</Setter>
</Style>
I get the following exception at runtime: Cannot add content of type 'System.Windows.Controls.Image' to an object of type 'System.Object'. Error at object 'System.Windows.Controls.Image' in markup file 'WpfApplication1;component/application.xaml' Line 164 Position 26.
In the other hand, this is the example in the above link:
<MenuItem Header="New">
<MenuItem.Icon>
<Image Source="data/cat.png"/>
</MenuItem.Icon>
</MenuItem>
Thanks.
回答1:
I have run into the same issue. I found the same error on aonther thread http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/81a106dd-4d06-4506-820a-30fe96a39112. According to their solution, you may try this one. But binding executes only for last element in MenuItem collection. It's so bad!
<Style x:Key="MenuItem_Delete" TargetType="MenuItem"
BasedOn="{StaticResource {x:Type MenuItem}}">
<Style.Resources>
<Image x:key="DeleteIcon" Source="Resources/Delete.png"/>
</Style.Resources>
<Setter Property="Header" Value="_Delete"/>
<Setter Property="MenuItem.Icon" Value="{DynamicResource DeleteIcon}" />
</Style>
Is there any update? Thanks!
回答2:
I was desperatly searching the web for an answer and I think this is a WPF bug.
I reported it @ Microsoft Connect, please vote and validate or share your ideas with Microsoft if you have some.
Update
This post helped me a lot.
回答3:
The next code will solve this issue.
<Style x:Key="StyleNewContext" TargetType="MenuItem">
<Style.Resources>
<Image x:Key="ImageNewContext" Source="{StaticResource ImageSourceNewContext}" />
<Image x:Key="ImageNewContextDisabled" Source="{StaticResource ImageSourceNewContextDisabled}" />
</Style.Resources>
<Setter Property="Icon" Value="{DynamicResource ImageNewContext}" />
<Style.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Icon" Value="{DynamicResource ImageNewContextDisabled}" />
</Trigger>
</Style.Triggers>
</Style>
Regards, Peter
来源:https://stackoverflow.com/questions/1495489/unable-to-set-system-windows-controls-menuitem-icon-thru-a-setter