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

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

  

和我的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’。任何人都可以帮我解释一下,谢谢

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

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

图像,标记为内容

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

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

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

图像,标记为资源

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

  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; 

我给出了下面的代码片段,将代码片段中提到的样式分配给按钮或切换按钮,然后您将完全由XAML控制更改的背景…无需其他编码。 我不是所有的代码只是试图理解背后的逻辑;)

   

如果未包含,请在项目中包含文件“Image \ Logo.png”。 然后通过访问该文件的属性选项卡(右键单击)将其构建操作设置为“Resource”。

设置构建资源的操作

另外,我不确定你在按钮的Click处理程序中尝试做什么。 您已经在XAML中设置背景图像。 除非您在Click处理程序中将其设置为另一个图像,否则不需要该代码。