如何在C# WPF中显示图像

问题描述 投票:0回答:1

我是一名计算机科学专业一年级学生,我在 C# 方面遇到了很大的困难。我接到一项任务,必须创建一个 wpf,其中必须显示图像,当我的鼠标落在这些图像上时,它们必须变得模糊。但我无法显示我的图像,我不知道为什么。它们在我的 XAML 中是正确的(我没有错误消息),并且我按照我的课程所述对它们进行了编码:

img(name).Source = new BitmapImages(new Uri(@"image/(name).png", UriKind.Relative));
,但由于某种原因它不起作用,我不明白为什么,我不想使用ChatGPT,希望你们能帮助我。

我试过:

img(name).Source = new BitmapImages(new Uri(@"image/(name).png", UriKind.RelativeOrAbsolute));

我也尝试过:

BitmapImage (name) = new BitmapImage(new Uri("img/(name).png", UriKind.Relative));
img(name).Source = (name); 

所以通常情况下,一旦我启动 wpf,图像就应该在那里,当我的鼠标经过图像时,它应该变得模糊。

c# wpf
1个回答
0
投票

以下内容应该可以帮助您入门。它显示了如何加载图像。至于模糊图像,我把它留给你来完成。

VS 2022

创建一个新项目:WPF App(.NET Framework)(名称:ImageTest)

打开解决方案资源管理器

  • 在 VS 菜单中,点击 View
  • 选择解决方案资源管理器

将图像添加到解决方案

  • 在解决方案资源管理器中,右键单击 (例如:ImageTest)
  • 选择添加
  • 选择新文件夹(名称:图像)
  • 在解决方案资源管理器中,右键单击刚刚创建的文件夹(例如:图像),选择添加
  • 选择现有项目...
  • 对于过滤器,选择:
  • 选择所需的图像(例如:Apple.png)

在解决方案资源管理器中,您现在将看到以下内容:

MainWindow.xaml

<Window x:Class="ImageTest.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:ImageTest"
        mc:Ignorable="d"
        Loaded="Window_Loaded"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="200" />
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="200" />
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>

        <!-- image control -->
        <Image Grid.Row="1" Grid.Column="1" x:Name="image1" />
    </Grid>
</Window>

MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
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 ImageTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Uri imgUri = new Uri("/Images/Apple.png", UriKind.Relative);
            image1.Source = new BitmapImage(imgUri);
        }
    }
}

资源

© www.soinside.com 2019 - 2024. All rights reserved.