70

我试过这个解决方案:

<Button>
    <StackPanel>
        <Image Source="Pictures/img.jpg" />
        <TextBlock>Blablabla</TextBlock>
    </StackPanel>
</Button>

但是我只能在项目窗口中看到图像,当我启动程序时它就消失了。

如果我试试这个:

  Image img = new Image();
  img.Source = new BitmapImage(new Uri("foo.png"));

  StackPanel stackPnl = new StackPanel();
  stackPnl.Orientation = Orientation.Horizontal;
  stackPnl.Margin = new Thickness(10);
  stackPnl.Children.Add(img);

  Button btn = new Button();
  btn.Content = stackPnl;

我在 PresentationFramework.dll 中收到“'System.Windows.Markup.XamlParseException'”异常。

解决办法是什么?

4

7 回答 7

83

在“丢失”图像的情况下,需要考虑几件事:

  1. 当 XAML 找不到资源时,它可能会忽略它(当它不会抛出XamlParseException.

  2. 必须正确添加和定义资源:

    • 确保它存在于您的项目中预期的位置。

    • 确保它是使用您的项目作为资源构建的。

      (右键→属性→BuildAction='Resource')

片段

在类似情况下尝试的另一件事,这对于重用图像(或任何其他资源)也很有用:

将图像定义为 XAML 中的资源:

<UserControl.Resources>
     <Image x:Key="MyImage" Source.../>
</UserControl.Resources>

然后在您想要的控件中使用它:

<Button Content="{StaticResource MyImage}" />
于 2013-07-07T20:06:36.507 回答
32

请尝试以下 XAML 代码段:

<Button Width="300" Height="50">
  <StackPanel Orientation="Horizontal">
    <Image Source="Pictures/img.jpg" Width="20" Height="20"/>
    <TextBlock Text="Blablabla" VerticalAlignment="Center" />
  </StackPanel>
</Button>

在 XAML 中,元素采用树结构。因此,您必须将子控件添加到其父控件。下面的代码片段也可以正常工作。为您的 XAML 根网格命名为“MainGrid”。

Image img = new Image();
img.Source = new BitmapImage(new Uri(@"foo.png"));

StackPanel stackPnl = new StackPanel();
stackPnl.Orientation = Orientation.Horizontal;
stackPnl.Margin = new Thickness(10);
stackPnl.Children.Add(img);

Button btn = new Button();
btn.Content = stackPnl;
MainGrid.Children.Add(btn);
于 2013-07-07T19:57:40.753 回答
11

利用:

<Button Height="100" Width="100">
  <StackPanel>
    <Image Source="img.jpg" />
    <TextBlock Text="Blabla" />
  </StackPanel>
</Button>

它应该工作。但请记住,您必须将图像添加到项目的资源中!

于 2013-07-07T20:02:46.573 回答
8

如果您想覆盖文本,可以将按钮的背景设置为图像。

<Button>
   <Button.Background>
     <ImageBrush ImageSource="/AssemblyName;component/Pictures/img.jpg"/>
   </Button.Background>
   <TextBlock>Blablabla</TextBlock>
</Button>

注意图像源语法。请参阅此问题寻求帮助。

于 2016-06-03T15:38:43.440 回答
7

我也有同样的问题。我已经使用以下代码修复了它。

        <Button Width="30" Margin="0,5" HorizontalAlignment="Stretch"  Click="OnSearch" >
            <DockPanel>
                <Image Source="../Resources/Back.jpg"/>
            </DockPanel>
        </Button>

注意:确保属性窗口中图像的构建动作应该是Resource.

在此处输入图像描述

于 2018-02-12T13:12:47.527 回答
3

尝试内容模板:

<Button Grid.Row="2" Grid.Column="0" Width="20" Height="20"
        Template="{StaticResource SomeTemplate}">
    <Button.ContentTemplate>
        <DataTemplate>
            <Image Source="../Folder1/Img1.png" Width="20" />
        </DataTemplate>
    </Button.ContentTemplate>
</Button>
于 2017-02-17T09:39:25.920 回答
1

我发现我还必须将“资源”选项卡中的“访问修饰符”设置为“公共”——默认情况下它设置为“内部”,并且我的图标仅出现在设计模式下,但在我运行应用程序时不会出现。

于 2018-06-11T07:59:10.097 回答