我正在嘗試製作一個應用程序,它可以在硬幣的標誌圖像和硬幣的尾部圖像之間切換。但是,每次按下「正面」按鈕或「反面」按鈕時,都會發生錯誤。如何修復我的代碼以便圖像成功切換?如何在C#WPF應用程序中切換圖像?
XAML:
<Window x:Class="HeadsOrTails.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:HeadsOrTails"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Image
x:Name="coinImage"
HorizontalAlignment="Center"
Height="100"
Margin="43,10,374,209"
VerticalAlignment="Center"
Width="100"
Loaded="Image_Loaded"/>
<Button x:Name="tailsButton" Content="Show Tails" HorizontalAlignment="Center" Height="40" Margin="190,214,197,65" VerticalAlignment="Center" Width="130" Click="tailsButton_Click"/>
<Button x:Name="headsButton" Content="Show Heads" HorizontalAlignment="Center" Height="40" Margin="43,214,344,65" VerticalAlignment="Center" Width="130" Click="headsButton_Click"/>
<Button x:Name="exitButton" Content="Exit" HorizontalAlignment="Center" Height="40" Margin="339,214,48,65" VerticalAlignment="Center" Width="130" Click="exitButton_Click"/>
</Grid>
</Window>
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace HeadsOrTails
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Image_Loaded(object sender, RoutedEventArgs e)
{
}
private void tailsButton_Click(object sender, RoutedEventArgs e)
{
//create a second bitmap image (tails)
BitmapImage c = new BitmapImage();
c.BeginInit();
c.UriSource = new Uri(@"C:\Users\Raymond\Documents\Visual Studio 2015\Projects\HeadsOrTails\tails.jpg");
c.EndInit();
var image = sender as Image;
image.Source = c;
}
private void headsButton_Click(object sender, RoutedEventArgs e)
{
//create the new bitmap image (heads)
BitmapImage b = new BitmapImage();
b.BeginInit();
b.UriSource = new Uri(@"C:\Users\Raymond\Documents\Visual Studio 2015\Projects\HeadsOrTails\heads.jpg");
b.EndInit();
var image = sender as Image;
image.Source = b;
}
private void exitButton_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
}
你能否更新你的問題來表明你正在得到什麼錯誤? –
請注意,請勿將邊距用於元素佈局。相反,在網格中定義行和列,並使用嵌套的佈局控件,例如一個帶有按鈕的StackPanel。 – Clemens