尝试在 WPF 中使用图像显示卡片,为什么它不起作用?

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

我试过在 WPF C# 中使用图像和位图图像来动态更改我在项目中显示的图像,但是它不起作用。我没有收到任何错误,如果我输入了不正确的来源,它会告诉我这是错误的,但是当我运行代码时它实际上并没有显示任何图片而没有任何错误。这是我要运行的 C# 代码:

        var mainwindow = new MainWindow(); //creating a link to the UI to access the image controls
        Players[i].Cards = new Card[2];
        Players[i].Cards[0] = Deck[i * 2];
        string Suit = Convert.ToString(Players[i].Cards[0].Suit);
        string Rank = Convert.ToString(Players[i].Cards[0].Rank);
        Image Card = new Image();
        BitmapImage source = new BitmapImage();
        source.BeginInit();
        source.UriSource = new Uri($@"C:\Users\User\Documents\Cards\{Suit}\{Rank}.png", UriKind.Relative);
        source.EndInit();
        Card.Source = source;

你可以假设来源是正确的,我已经测试过了。

我已经尝试了很多东西,比如只使用位图控件和静态图像源,这不是我想要使用的,但即使这样也没有用。我需要更改任何设置才能使其正常工作吗?如果我将源代码直接加载到 XAML 代码中,它确实可以工作,但我无法根据发到的牌更改它。任何帮助将不胜感激!

c# wpf xaml data-binding wpf-controls
1个回答
0
投票

你应该简单地直接初始化

BitmapImage

BitmapImage source = new BitmapImage(new Uri($@"C:\Users\User\Documents\Cards\{Suit}\{Rank}.png"));

注意:您指定了相对类型的 uri,但实际上使用的是我遗漏的完整路径。

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