Wpf почему не отображается картинка
Перейти к содержимому

Wpf почему не отображается картинка

  • автор:

Image не отображается

Не отображается Image
Доброго времени суток, знаю, что много раз задавали этот вопрос, но я искал, и ничего не помогло.

Не отображается Image в TabItem
Добрый День, Подскажите что я делаю не так? не видно картинки 🙁 Спасибо!

Не отображается картинка загруженная в image
Не отображается картинка загруженная в image, но при этом она видна сбоку, но в окне почему то не.

Image не отображается после запуска
пустой проект, в конструкторе все показывает, после компиляции форма пустая. при том в другом.

Вложения

WpfApplication2.rar (72.4 Кб, 86 просмотров)

Спасибо, заработало. Хотя я вчера и так и так пробовал, ничего не работало

А ещё мне интересно как так сделать расплывчатой панель задач?

Сообщение от BORIS_HERE

уже дожились, что и эта вся перечисленная фигня не работает!
Как можно делать эти говённые студии, чтобы в проекте всё отображалось, но призапуске — белый экран.
И ресурсы и Content при построении проекта указаны, и картинка находится в ресурсах и путь к ней указан, и в проекте она вида, но тупо не загружается при запуске. Вот я не могу взять в толк, как выразить мысль иначе, но кроме матов у меня нет больше аргументов. Пусть модераторы забанят этот комментарий, что скорее всего произойдёт, потому что реальные проблемы далеки от ученических ванильных статей на этом сайтике.

Добавлено через 5 минут

Добавлено через 1 минуту

yurii_kutuzov, скиньте проект — посмотрю.

Добавлено через 2 минуты
А в целом, к конструктору Студии нареканий много. Он помогает сделать первые шаги, особенно, начинающим после WinForms. Но дальше больше мешает чем помогает. Поэтому реально XAML делается не в конструкторе, а пишется в редакторе.

Изображение в кнопке WPF не отображается во время выполнения

Все, у меня есть следующее начало небольшому приложению, которое проверяет файлы .resx на согласованность встроенных скобок (так что ошибки времени выполнения несоответствующих строк «. <0>» не происходят). У меня есть следующий XAML для MainWindow.xaml, и моя конкретная проблема связана с изображением, которое должно отображаться на кнопке

У изображения есть «Build Action = Resource», «Copy to output directory = Do not copy» — изображение отображается в дизайнере, но не во время выполнения. Я видел следующие вопросы и читал соответствующие ответы, но никто не решает проблему:

Как получить изображение кнопки во время выполнения?

7 ответов

Измените действие сборки на «Ресурс». Также неправильный URL-адрес вашего пакета. Либо используйте:

1: Измените настройки изображения:

2: При использовании приложения вместо siteoforigin в исходном пути вам необходимо:

a) Изображение будет в SubFolder под названием «Ресурсы», а файл .exe будет небольшим.

b) Изображение будет включено в .exe, и никакая подпапка с файлом изображения не будет существовать

Предположим, что у вас

установите Build Action в Resource

правильно установить этот путь, используя URI-PACK-FORMAT

В моем случае он все еще не показывался.

Clean & Rebuild Не просто Build исправил его для меня!

В моем случае у меня были изображения в отдельном проекте с именем Common , а изображения находились под папкой с именем Resources в этом проекте. В моем другом проекте я добавил ссылку на Common и установил источник изображений следующим образом:

У изображений Build Action установлено значение Resource и Copy to Output Directory на Do not copy . Однако по какой-то странной причине он не работал, пока я не удалил каждый файл сборки в своем решении и не сделал Clean Solution и Build Solution . Не уверен, почему, но все это началось во время выполнения, как только я перестроил все. Я все еще не могу понять, почему он работал в Design Time, хотя.

Перейдите к своему изображению в папке ресурсов, щелкните правой кнопкой мыши по изображению, перейдите к свойствам. Щелкните свойство BuildAction и установите для него значение Ресурс из none. Это будет работать.

Я определил свое изображение следующим образом:

Изображение отображается в дизайнере Visual Studio, но при запуске приложения изображение не отображается! Это сделало меня сумасшедшим! Я пробовал все Build Actions с помощью clean/build, не повезло.

В моем случае проблема связана с тем, что элемент управления (который использует Image) и само приложение находится в разных проектах. Ресурсы/Картинки находятся в проекте Controls. В результате приложение попыталось найти icon.png в собственной папке Debug, но на самом деле оно находится в папке Debug от Controls.

Итак, для меня работают два решения:

1) поместите ресурсы/изображения в проект приложения (не так хорошо, когда есть несколько проектов, которые используют элементы управления из проекта Controls, но он работает)

Wpf почему не отображается картинка

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Visual studio home link

  • ProfileText
  • Sign in

Answered by:

Question

Today i sat down and decided to do some more work with WPF and i decided to try some stuff out with various images. But when i went to place a PNG image into my window it doesn’t display. To clarify further i can see the PNG image in both the Visual Studio and Blend designers, but as soon as i run my app and the window loads with the PNG on it, i don’t see the PNG any more. Also, this same pattern seems to be happening with various other images that i have. Some work and others don’t and all of them are included in the project in the root directory.

If anyone can help me out on this that would be great.

Here is the code if it makes any difference, although as you will see i am not doing anything out of the ordanary.

< Window
xmlns = » http://schemas.microsoft.com/winfx/2006/xaml/presentation »
xmlns:x = » http://schemas.microsoft.com/winfx/2006/xaml »
xml:lang = » en-US »
x:Class = » CodeGuru.Window10 »
x:Name = » Window »
Title = » Window10 »
Width = » 640 » Height = » 480 » >
< Grid x:Name = » LayoutRoot » >
< Image Source = » shows.jpg » />
< Image Source = «doesntshow .jpg » />
</ Grid >
</ Window >

Answers

i mean in Visual studio you can right click on the image — properties window — copy property . you can also manually edit the csproj file to do the same

not wpf image property 🙂

Hi Anthony, I received your solution file, and it appears to have two seperate issues:

(1) Siteoforigin files need to follow the following syntax: (you need to include the «. «)

<Image Source Courier New»> teoforigin. / ImageFileName» />

(2) You need to either manually copy the image files to the same directory of your application executable or, as Lester mentioned above, include them in your VS project as content and set «Copy To Output Directory» property to either «Always copy» or «Copy If Newer» (VS will do the copying for you)

I have emailed you back two seperate projects demonstrating how to reference images from Resource and from SiteOfOrigin. Please take a look and let me know if you still have problem. Also, try cleaning the solution before rebuild just to be sure any changes you made are included.

All replies

Hi Anthony, did you include those images as part of your Visual Studio project? If not, they need to be included as Resources and build with the application. Alternatively, you may also try loading those images from SiteOfOrigin by changing the Image Source property to the following:

<Image Source="pack://siteoforigin. /shows.jpg" />

<Image Source="pack://siteoforigin. /doesntshow.jpg" />

Please let me know if this helps.

Thanks for the quick response. Just confirming for you that yes i did explicitly include the images into my project and that i also tried your suggestion of using siteoforrigin and it made no difference. To be sure i created a new project and took the images from the old project and included them in this new project and the same thing happened — can see is VS and blend designers but not in the running application. Also just to be sure i tried using and a couple of alternative images to the ones i was using and the same thing happened.

One thing i do know is that it was working before because in the past i have been able to use images. But for some reason i can anymore. The only thing that i can think of if it is not a WPF problem, is that AROUND (i am not 100% sure whether it was working just before of just after) when it did work and now it doesn’t, is that i got the latest round of windows XP updates and i updated VS to SP1. In saying though i don’t think it would be VS SP because i have to exact same thing happen in Blend.

Also if it makes a different if i use open an exciting project that has images in it, the app runs fine, but any new images that i try to include don’t. But given all this it could be something that i am doing, but i dought it, because as far as i know all you have to do to start using and image is to copy and past it into the project folder and then include it in the project. Then as long as you have to paths right it should work. If there is a process i have left out here then it could be that that is causing the issue, otherwise it’s something else.

Image not displaying at runtime C# WPF

I am trying to display an image in WPF but for some reason, the image won’t show! It appears on the Visual Studio editor but when I run the application it doesn’t appear.

Here is some of my code:

This is how I’m trying to display the image:

I have also tried using this:

12 Answers 12

In your project:

  1. Create a folder say "img", right click on it and select add existing item add image to folder
  2. Go to properties of the added image, set Build Action as Resource .

It worked for me.

If none of these work, try changing the Build Action to Content.

That’s what worked for me after struggling for a long time with this.

Go to the properties for the image in Visual Studio and change «Build Action» to «Resource» and «Copy to Output Directory» to «Copy if newer».

I had to do a rebuild, but then it worked. Cred to swapnil.

please drag the image to a image source,it will be like this /img/image.jpg»/

Harjeet Singh's user avatar

If none of the above works, try Rebuilding your application from the build menu. Not "Build", but "Rebuild"

Tyler Pantuso's user avatar

For example, this is your project structure

and you want to access the to amogus.png in your xaml window, You have two ways:

note this way the imagesFolder will be visible in the release build to users

  1. to set amogus.png Build Action to Content and Copy to Output Directory to Copy always more info, then rebuild from the build menu, then add this to the window xaml

note this way the imagesFolder will be not visible in the release build to users

  1. to set amogus.png Build Action to Resource and Copy to Output Directory to Do not copy or blank more info, then rebuild from the build menu, then add this to the window xaml

RoadRoller01's user avatar

  1. Right click your project name in solution explorer and select Add -> New Folder .
  2. Name this folder as Images
  3. Right click to Images folder and select Add -> Existing item and then select your image.png file
  4. On your image.png properties adjust build action -> Resource
  5. Now your image source is Source="Images/image.jpg"
  6. You should see your image on design window of VS. Do not forget to clean code before compiling

Right click images on the Solution Explorer, choose Properties and then set the Build Action as Resource.

Did not have to do a clean and rebuild. I tried every combination listed above (I am in VS2017)

  1. Go to Project->Properties->Resources
  2. Select File (drop down with choices of strings, images, icons. )
  3. Click Add Resource->Existing File
  4. Navigate to the image and import it
  5. VS identifies it as an image (mine is PNG) and switches the view to show Image resources
  6. Select the thumbnail of the image and in the Properties of the Image (type should be Bitmap) set Persistence to Embedded in resx
  7. I saved and closed Project Properties as I got confused here before
  8. Go to the Resources folder under the project and select the image (it should be listed for you)
  9. Select the image and set the BuildAction to Embedded Resource
  10. I set the File Action to Copy if Newer

From here I move back and forth between Debug and runtime, various combinations of clean, build and publish and the image has FINALLY been displayed every time.

Last tidbit, the XAML in the dialog looks like this:

I have updated several projects that were supposed to display graphics but didn’t always do so using the steps above. They all work now. Tested in both VS2017 and VS2019 and no errors so far.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *