【问题标题】:Resource image can be referenced in Xaml but not in code, why?资源图像可以在 Xaml 中引用,但不能在代码中引用,为什么?
【发布时间】:2014-02-11 11:13:08
【问题描述】:

请原谅新手的问题,但我只是在学习 WPF。 我有一张图片,我已将构建操作设置为“资源”

如果我将它设置为 XAML 中的窗口图标,它就可以正常工作。 像这样:

Window ... Icon="Images/MyIco.png"

但是,如果我尝试将其设置为图像的来源,则会出现找不到资源的异常:

Uri uri = new Uri("pack://application:,,,/Images/MyIco.png"); // This does not work
img.Source = BitmapFrame.Create(uri); 

我在上面的代码中做错了什么?

【问题讨论】:

    标签: c# wpf image xaml resources


    【解决方案1】:

    确保你的路径是正确的,如果是真的,你可以试试这个代码来加载你的图片

        //tmp is your path
        BitmapImage img = new BitmapImage(new Uri(tmp, UriKind.Relative));
        img.CreateOptions = BitmapCreateOptions.None;
        img.ImageOpened += img_ImageOpened;
    
        void img_ImageOpened(object sender, RoutedEventArgs e)
        {
            WriteableBitmap wbm = new WriteableBitmap((BitmapImage)sender);                
        }
    

    例如:我的路径是“/Assets/sizes/background/bg_02.png”

    【讨论】:

    • 如您所见,路径是正确的,因为它适用于 Icon="Images/MyIco.png" 我试图了解 Uri 的路径字符串是否有问题:“pack ://application:,,,/Images/MyIco.png"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多