如何在 C# WPF 代码中更改设置按钮的背景图像? [英] How to changeset background image of a button in C# WPF code?

查看:26
本文介绍了如何在 C# WPF 代码中更改设置按钮的背景图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to change background image of my button to some other image and I encountered some errors. This is the code I have on my 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>

和我的 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;
    }

我在 xaml 上的错误是文件 'Imageslogo.png' 不是项目的一部分,或者它的 'Build Action' 属性未设置为 'Resource'.谁能帮我解释一下,谢谢

The error I have on my xaml is " The file 'Imageslogo.png' is not part of the project or its 'Build Action' property is not set to 'Resource'. Can anyone help me explain, thanks

推荐答案

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

In the build action, you can mark the image file as content or as resource. The syntax to use the image in an ImageBrush is different depending on which one you choose.

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

Here is a image file marked as content.

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

To set the button background to this image use the following code.

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

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

Here is an image file marked as resource.

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

To set the button background to the resource image use the following code.

  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;

这篇关于如何在 C# WPF 代码中更改设置按钮的背景图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆