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

查看:1518
本文介绍了如何在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上的错误是文件'Images \ logo .png'不是项目的一部分,或者它的'Build Action'属性没有设置为'Resource'。
任何人都可以帮我解释一下,谢谢

The error I have on my xaml is " The file 'Images\logo.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;

这里是标记为资源。

要设置资源图像的按钮背景,请使用以下代码。

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天全站免登陆