c# - 在 wpf c# 中单击更改按钮图像

标签 c# wpf xaml

我正在使用 xaml 和 c# 为 Windows 8.1 商店创建一个井字游戏,并试图在单击时更改 X 和 O 按钮。最初,我在按钮的 xaml 中设置了一个空白图像,在 button_click 事件中,我试图更改图像源。这是我的代码片段:

private void Button_Click(object sender, RoutedEventArgs e)
    {
        Button btn = sender as Button;
        if (turn == 1)
        {
            BitmapImage bmp = new BitmapImage();
            Uri u = new Uri("ms-appx:/Images/O_logo.png", UriKind.RelativeOrAbsolute);
            bmp.UriSource = u;
            ImageBrush i = new ImageBrush();
            i.ImageSource = bmp;
            btn.Background = i;
        }
        else
        {
            BitmapImage bmp = new BitmapImage();
            Uri u = new Uri("ms-appx:/Images/X_logo.png", UriKind.RelativeOrAbsolute);
            bmp.UriSource = u;
            ImageBrush i = new ImageBrush();
            i.ImageSource = bmp;
            btn.Background = i;

        }
        btn.IsEnabled = false;
        //win(btn.Content.ToString());
        turn += 1;
        if (turn > 2)
            turn = 1;
    }

我在网上阅读了几篇文章,其中一些文章建议我将图像的构建操作设置为资源,但我没有将其作为选项。我有 PRIResource 和 Embedded Resource 作为选项。我对 mvvm 和触发器的了解非常有限,因此想使用 wpf 本身而不是 xaml 来解决问题。

我正在使用 VS Studio Professional 2013

最佳答案

Background 当按钮被禁用时不显示。您应该将 Image 作为按钮内容:

private void Button_Click(object sender, RoutedEventArgs e)
{
    Button btn = sender as Button;
    if (turn == 1)
    {
        BitmapImage bmp = new BitmapImage();
        Uri u = new Uri("ms-appx:/Images/O_logo.png", UriKind.RelativeOrAbsolute);
        bmp.UriSource = u;
        // NOTE: change starts here
        Image i = new Image();
        i.Source = bmp;
        btn.Content = i;
    }
    else
    {
        BitmapImage bmp = new BitmapImage();
        Uri u = new Uri("ms-appx:/Images/X_logo.png", UriKind.RelativeOrAbsolute);
        bmp.UriSource = u;
        // NOTE: change starts here
        Image i = new Image();
        i.Source = bmp;
        btn.Content = i;

    }
    btn.IsEnabled = false;
    //win(btn.Content.ToString());
    turn += 1;
    if (turn > 2)
        turn = 1;
}

我还强烈建议您学习并开始使用 XAML 和绑定(bind),而不是避免使用它。您实际上是在以您使用它的方式与 WPF 作斗争,并使它对您自己来说更加困难。如果您按预期使用它,您可能会发现它优于 Windows 窗体。

关于c# - 在 wpf c# 中单击更改按钮图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23233735/

相关文章:

c# - 如何在 C# 中强制使用方法的返回值?

c# - 检查 SignalR 属性中的授权

wpf - WPF应用程序中的任务栏丑陋的图标

c# - 如何治愈C# winforms图表的摆动?

c# - DotCover 不覆盖引用的 DLL

CSS 文件中的 C#? (ASP.NET MVC 5)

Azure 上的 WPF 和 Squirrel 部署

c# - 在 WPF 中将 XML 绑定(bind)到 Treeview 的简单方法

c# - 如何在自定义 MarkupExtension 中处理 Freezable?

wpf - 根据单元格的内容设置 DataGridRow 的背景