如何在C#WPF代码中更改\设置按钮的背景图像?

Jaz*_*Jaz 8 c# wpf image button

我正在尝试将我的按钮的背景图像更改为其他图像,但我遇到了一些错误.这是我在xaml上的代码:

    <Button x:Name="Button1" Width="200" Height="200" Content="Button1" Margin="0,0,0,400">
        <Button.Background>
            <ImageBrush **ImageSource ="Images/AERO.png"**  ></ImageBrush>
        </Button.Background>
    </Button>
Run Code Online (Sandbox Code Playgroud)

和我的cs:

    private void Button1_Click_1(object sender, RoutedEventArgs e)
    {
        var brush = new ImageBrush();
        brush.ImageSource = new BitmapImage(new Uri("Images/AERO.png"));
        Button1.Background = brush;
    }
Run Code Online (Sandbox Code Playgroud)

我在我的xaml上的错误是"文件'Images\logo.png'不是项目的一部分,或者它的'Build Action'属性没有设置为'Resource'.任何人都可以帮我解释一下,谢谢

Wal*_*her 15

在构建操作中,您可以将图像文件标记为内容或资源.在ImageBrush中使用图像的语法因您选择的图像而异.

这是标记为内容的图像文件.

图像,标记为内容

要将按钮背景设置为此图像,请使用以下代码.

 var brush = new ImageBrush();
 brush.ImageSource = new BitmapImage(new Uri("Images/ContentImage.png",UriKind.Relative));
 button1.Background = brush;
Run Code Online (Sandbox Code Playgroud)

这是一个标记为资源的图像文件.

图像,标记为资源

要将按钮背景设置为资源图像,请使用以下代码.

  Uri resourceUri = new Uri("Images/ResourceImage.png", UriKind.Relative);
  StreamResourceInfo streamInfo = Application.GetResourceStream(resourceUri);

  BitmapFrame temp = BitmapFrame.Create(streamInfo.Stream);
  var brush = new ImageBrush();
  brush.ImageSource = temp;

  button1.Background = brush;
Run Code Online (Sandbox Code Playgroud)