我为工具栏内的按钮创建了一个样式,该样式是图标和文本的组合:
<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'.
但是在设计时一切正常...
如何解决此问题?
编辑(解决方法)
我从按钮声明中删除了内容属性:
<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>
<Button Name="Bt_Import" Command="{Binding Path=CmdImport}" Style="{StaticResource BtStyle_ToolBar}">
<StackPanel>
<TextBlock Text="{x:Static p:Resources.Import}"/>
<Image Source="Resources/import_16x16.png"/>
</StackPanel>
</Button>
或者只是在模板级别设置它。
<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="Resources/import_16x16.png" />
<TextBlock Text="Awesome"
VerticalAlignment="Center" />
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
嗯
,你有没有注意到它抱怨的图像是export_excel_16x16.png,但你发布的 XAML 正在谈论import_16x16.png。您确定您没有误解错误的原因吗?即您在其他地方有 XAML,这就是问题所在。克里斯W.是正确的,也检查图像的构建操作。
谢谢