我为工具栏内的按钮创建了一种样式,它是图标和文本的组合:
<Style TargetType="{x:Type Button}" x:Key="BtStyle_ToolBar">
<Setter Property="Foreground" Value="White" />
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="FontFamily" Value="Segoe UI" />
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate DataType="{x:Type Button}">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Button}, Path=Tag}" />
<TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Button}, Path=Content}"
VerticalAlignment="Center" />
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
使用它:
<Button Name="Bt_Export" Content="{x:Static p:Resources.Export}" Command="{Binding Path=CmdExport}"
Padding="5" Style="{StaticResource BtStyle_ToolBar}" Tag="Resources/export_excel_16x16.png"/>
问题是在运行时会向即时窗口抛出异常:
System.Windows.Data Error: 6 : 'ObjectSourceConverter' converter failed to convert value 'Resources/export_excel_16x16.png' (type 'String'); fallback value will be used, if available. BindingExpression:Path=Tag; DataItem='Button' (Name='Bt_Export'); target element is 'Image' (Name=''); target property is 'Source' (type 'ImageSource') IOException:'System.IO.IOException: Cannot locate resource 'themes/resources/export_excel_16x16.png'.
但在设计时一切正常......
我该如何解决这个问题?
编辑(解决方法)
我从按钮声明中删除了 content 属性:
<Button Name="Bt_Export" Style="{StaticResource BtStyle_ToolBar}">
<DockPanel>
<Image Source="/Resources/export_excel_16x16.png"/>
<TextBlock VerticalAlignment="center" Text="{x:Static p:Resources.Export}"></TextBlock>
</DockPanel>
</Button>