你不能使用sender
参数,因为那是按钮,而不是图像控件。
Use the coinImage
改为成员:
private void headsButton_Click(object sender, RoutedEventArgs e)
{
coinImage.Source = new BitmapImage(new Uri(@"C:\Users\Raymond Karrenbauer\Documents\Visual Studio 2015\Projects\HeadsOrTails\heads.jpg"));
}
private void tailsButton_Click(object sender, RoutedEventArgs e)
{
coinImage.Source = new BitmapImage(new Uri(@"C:\Users\Raymond Karrenbauer\Documents\Visual Studio 2015\Projects\HeadsOrTails\tails.jpg"));
}
除此之外,您应该将这两个图像文件添加到您的 Visual Studio 项目中,设置它们的Build Action
to Resource
并通过访问它们资源文件包 URI。这样你就不必处理绝对文件路径:
private void headsButton_Click(object sender, RoutedEventArgs e)
{
coinImage.Source = new BitmapImage(new Uri("pack://application:,,,/heads.jpg"));
}
private void tailsButton_Click(object sender, RoutedEventArgs e)
{
coinImage.Source = new BitmapImage(new Uri("pack://application:,,,/tails.jpg"));
}
然后,您还可以将 BitmapImages 添加为 XAML 资源:
<Window ...>
<Window.Resources>
<BitmapImage x:Key="heads" UriSource="heads.png"/>
<BitmapImage x:Key="tails" UriSource="tails.png"/>
</Window.Resources>
...
</Window>
并像这样使用它们:
private void headsButton_Click(object sender, RoutedEventArgs e)
{
coinImage.Source = (ImageSource)Resources["heads"];
}
private void tailsButton_Click(object sender, RoutedEventArgs e)
{
coinImage.Source = (ImageSource)Resources["tails"];
}