如何在运行时更改按钮的背景图像?

我遇到了问题。 我想在运行时更改按钮的背景图像。 我得到了改变颜色的解决方案,但我想改变图像。

代码如下

public void buttonCase(object sender, RoutedEventArgs e) { Uri uri = null; var image = new ImageBrush(); if (((App)App.Current).appControler.m_Mode == Controller.textMode.Letters) { ((App)App.Current).appControler.buttonCase(sender, e); switch (((App)App.Current).appControler.m_case) { case Controller.caseMode.Upper: b0.FontSize = b1.FontSize = b2.FontSize = b3.FontSize = b4.FontSize = b5.FontSize = b6.FontSize = b7.FontSize = b8.FontSize = b9.FontSize = bCornerLower.FontSize = 30.0; uri = new Uri(@"/SourceCode;component/Images/Lower_Case_p.png", UriKind.Relative); image.ImageSource = new BitmapImage(uri); btnCase.Background = image; break; case Controller.caseMode.Lower: b0.FontSize = b1.FontSize = b2.FontSize = b3.FontSize = b4.FontSize = b5.FontSize = b6.FontSize = b7.FontSize = b8.FontSize = b9.FontSize = bCornerLower.FontSize = 40.0; uri = new Uri(@"/SourceCode;component/Images/Case_p.png", UriKind.Relative); image.ImageSource = new BitmapImage(uri); btnCase.Background = image; break; } } } 

像这样的东西?

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

[编辑]我用两张图片制作了一个测试应用程序。 我在点击按钮时切换图像并且它可以工作。

 private bool flag; private void button1_Click(object sender, RoutedEventArgs e) { flag = !flag; var uriString = flag ? @"Images/logo.png" : @"Images/icon.png"; myButton.Background = new ImageBrush { ImageSource = new BitmapImage(new Uri(uriString, UriKind.Relative)) }; } 
 private void button_Click(object sender, EventArgs e) { button.Image=System.Drawing.Image.FromFile("image.png"); } 

试试这个..

利用VisualStates进行这种UI状态切换。 你的代码背后会是这样的:

 public void buttonCase(object sender, RoutedEventArgs e) { if (((App)App.Current).appControler.m_Mode == Controller.textMode.Letters) { ((App)App.Current).appControler.buttonCase(sender, e); switch (((App)App.Current).appControler.m_case) { case Controller.caseMode.Upper: VisualStateManager.GoToState( this, "UpperCase", true ); break; case Controller.caseMode.Lower: VisualStateManager.GoToState( this, "LowerCase", true ); break; } } } 

你的xaml看起来像这样:

            Visible       Collapsed                       40                     

我在这里写了代码作为类似问题的答案: 用不同的图像切换按钮

我知道定义VisualStates看起来相当麻烦,但最终你可以保持你的代码非常干净,从切换所有ui位和碎片的视觉外观。