如何在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处理程序中将其设置为另一个图像,否则不需要该代码。
- Facebook .NET SDK:如何使用ASP.NET MVC 2进行身份validation
- Response.Redirect无法在Global.asax中工作
- EntityFramework.dll中出现“System.InvalidOperationException”类型的exception,但未在用户代码中处理
- Asp.Net Web服务:我想返回错误403禁止
- XmlSerializer序列化空变量以使用两个标签?
- WPF本地化:带StringFormat的DynamicResource?
- 在mvc 4中使用HTML帮助程序选择下拉列表
- 未在项目的层次结构中找到新元素
- 该文档已有一个’DocumentElement’节点