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

标签 c# .net silverlight xaml windows-phone-7

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

代码如下

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)) };
}

关于c# - 如何在运行时更改按钮的背景图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6327074/

相关文章:

c# - 在 DataGridView 中将字符串转换为日期时间

c# - 如何在c#中使用open cv检测目标上的弹孔

silverlight - 同一端口上的多个套接字与多个端口上的多个套接字

c# - 使用 BackgroundAgent 时程序集丢失

c# - 如何验证 MVC 4 模型中的 IEnumerable<string> 属性

c# - 可以为字典创建匿名类型的隐式转换吗?

c# - 使用 Base64 编码将字节数组转换为 SecureString 的安全方法

c# - 什么使 LINQ 关联成为 EntitySet<table>?

c# - 如果我等待一个已经在运行或运行的任务,会发生什么?

c# - Silverlight 5 双击总是将 ClickCount 返回为 1