Include image in a project - wpf

I want to include an image in my project from behind-code, in order to permit me to set the image as fill of my rectangle!
I'm inserting an image in this way:
<Rectangle Grid.Column="2" Grid.Row="2" Margin="4,4,4,4" Style="{DynamicResource rectangle_style}" >
<Rectangle.Fill>
<ImageBrush ImageSource="image.jpg" Stretch="UniformToFill"/>
</Rectangle.Fill>
</Rectangle>
For create this background image I must include the image file in a project with right click on file and set "include in a project".
Can you help me to include the image from behind-code in run time, because I will have necessity to set image from most file in a folder!

One way is to do "Include in Project" or "Add existing item" and under Properties, set "Copy Local" to Always.
Note in this case, you need to get the application folder path
<ImageBrush ImageSource="c:\[YourPath]\[YourProject]\someImg.png" Stretch="UniformToFill" />
Or bind to a method that provides the current application path for you. (Do a search for this as there are many such questions answered on SO).
This means when you deploy the app, you have to deploy the image with it (it'll end up in the bin folder with whatever path structure you give it).
Another way is to do the same, and set Build Action to Resource - this will make your application compile with the image inside the DLL. Downside is the DLL will be larger, but you won't have to remember to copy the file when you deploy.
Access the resource by name (no front slash)
<ImageBrush ImageSource="someImg.png" Stretch="UniformToFill" />
Hope it helps!

Related

how use icon [Font-awesome] in WPF

I am new in WPF. I want to use Font-awesome Icon in textbox and button. but the icon is not bind with my textbox
I install Font-awesome resource to my application.
Let me know the way how can I use it
Thank You,
I really need it please help me..
Example
Step 1 : Download Font-Awesome
Tools -> Library Package Manager -> Package Manager Console
Install
PM > Install-Package FontAwesome.WPF
Step 2 : Add Resource
<Application> xmlns:fa="http://schemas.fontawesome.io/icons/" </Application>
Step 3 : Put App.xaml
<Application.Resources>
<Style x:Key="FontAwesome">
<Setter Property="TextElement.FontFamily" Value="pack://application:,,,/fonts/#FontAwesome" />
</Style>
</Application.Resources>
Step 4 : Use it in Demo.xaml
<TextBlock Style="{StaticResource FontAwesome}"
FontSize="75"
Text="" />
Step 5 :- Output
First, download Font Awesome, extract the ZIP file and copy fonts/fontawesome-webfont.ttf into a Fonts folder in your solution. Set the Build Action in the properties to Resource if it isn’t already
Next, add a Style to the Resources in App.xaml. Don’t forget the # at the front of the font name and remember to use the internal name of the font, not the name of the file. To check the name of the font, just double click on the font file and it will open in the Windows Font Viewer. The font name will be at the top.
<Application.resources>
<FontFamily x:Key="FontAwesome">/Fonts/fontawesome-webfont.ttf#FontAwesome</FontFamily>
</Application.resources>
Open MainWindow.xaml and replace the grid with below snippet:
<Grid VerticalAlignment="Center" HorizontalAlignment="Center">
<StackPanel Orientation="Horizontal" >
<TextBlock Text="I" FontSize="32" Margin="10" VerticalAlignment="Center"></TextBlock>
<TextBlock x:Name="tbFontAwesome" Text="" FontFamily="{StaticResource FontAwesome}" Foreground="Red" FontSize="32" Margin="10" VerticalAlignment="Center"></TextBlock>
<TextBlock Text="Font Awesome" FontSize="32" Margin="10" VerticalAlignment="Center"></TextBlock>
</StackPanel>
</Grid>
Notice "Text" property of "tbFontAwesome" textblock, its the Unicode for Heart.
Cheat Sheet
To extend the accepted answer because it's somewhat out of date and missing information, here's what I did:
Download FontAwesome
Unzip the archive
Inside the unzipped folder, under the use-on-desktop folder, locate the version you want. N.B. Solid has the most icons free; some icons require a Pro payment for Regular and Light versions.
For me, this was Font Awesome 5 Free-Solid-900.otf.
Following the accepted answer and most tutorials, first create a sub-folder in your C# project named Fonts. Paste the fonts file inside this folder.
I renamed this file FontAwesome.otf for brevity
Set the properties of this file:
Build Action: Resource
Copy to Output Directory: Copy if newer/Copy always
In your App.xaml <Application.Resources> or other <ResourceDictionary>, insert:
<FontFamily x:Key="FontAwesome">/YOUR_PROJECT_NAME;component/Fonts/FontAwesome.otf#Font Awesome 5 Free Solid</FontFamily>
Replace YOUR_PROJECT_NAME with your project name. I include this because it is needed should you use MergedDictionaries across projects.
If you did not place the file in a project sub-folder Fonts, rename or omit this part of the path.
Check that the filename matches: replace FontAwesome.otf with the filename (or rename the file itself).
Check the internal font name. You can do this by following the accepted answer. (Open the .otf or .tff file from explorer to start Windows Font Viewer, copy the font name).
Replace the Font Awesome 5 Free Solid with the font name (after the #).
Do not install the font otherwise you cannot verify that you have followed these steps correctly and the font may not work across computers that do not have the font installed.
I know this is an old question, and this option may not have been available to you at the time, so I thought I would provide an updated method for anyone who stumbles across this. I recommend you install the NuGet package 'FontAwesome5' from here:
FontAwesome5 on NuGet.org
or search "fontawesome5" in Visual Studio's built-in NuGet Package Manager window:
Tools > NuGet Package Manager > Manage NuGet Packages for Solution...
-it is usually the top result when using this exact search term.
Then simply add the following namespace to your XAML document:
xmlns:fa5="http://schemas.fontawesome.com/icons/"
and then you should find relative ease in adding icons to your project. For example:
<fa5:ImageAwesome Icon="Solid_ExclamationTriangle" Foreground="#FFFF7400"/>
or
<fa5:FontAwesome Icon="Solid_ExclamationTriangle" Foreground="#FFFF7400"/>
And the beauty of this is that IntelliSense will show you a list of all available icons, saving you the hassle of going to the website to search them up.
You could as well manually select FontAwesome from the FontFamily property of the TextBlock.That will solve the problem.
If FontAwesome is not among the list of fonts then you probably need to import the font file just like the first answer suggested.

Background Image of Button not showing in WPF

I have program in which I have lots of buttons. Each of button has background set as
<Button x:Name="mybutton" HorizontalAlignment="Left" Height="30" Margin="76,110,0,0" VerticalAlignment="Top" Width="25" Click="some_click">
<Button.Background>
<ImageBrush ImageSource="Resource/button_picture.png"/>
</Button.Background>
</Button>
Image is showing as background in .xaml when program not running but when i run application image is not there as background of button. How do i debug this background in button ? Is there any goofy error that is there?
Let's make sure we have the following properties set right in your scenario
1) Build Action -> Resource
2) Copy to Output Directory -> Do not copy
3) Instead of using the relative path for image source, try using a full path to the image like this (I say this because I don't know where the image resource is located in your project, using relative path is perfectly normal in WPF)
<Image Source="pack://application:,,,/AssemblyNameContainingImageResource;component/Resource/button_picture.png" />
You need to change the code like this
<Button x:Name="mybutton" HorizontalAlignment="Left" Height="30" Margin="76,110,0,0" VerticalAlignment="Top" Width="25" Click="some_click">
<Image Source="Resource/button_picture.png"/>
</Button>
Change the Build Action of button_picture.png to Resource if it is content. Also check the Copy to output directory property value

accessing image files from a separated assembly

I have several image files I want to share between projects(common icons) I have them in an assembly that would be in every solution I create...I have the files in a folder called Icon and I have the build as content copy always. I have verified that a folder is created with these icons...however my other assemblies are not able to find them...
<r:RibbonGroup Header="Users">
<r:RibbonButton >
<r:RibbonButton.LargeImageSource>
<BitmapImage UriSource="..\Icons\UserIcon.png" />
</r:RibbonButton.LargeImageSource>
</r:RibbonButton>
</r:RibbonGroup>
i have tried formatting the uri several ways...but it never succeeds. If the icons are in the actual assembly though they work...
Try using an absolute Uri. Build action must be set to Resource for UserIcon.png
<BitmapImage UriSource="pack://application:,,,/NameOfImageAssembly;component/Icons/UserIcon.png"/>
Relative Uri should also work
<BitmapImage UriSource="/NameOfImageAssembly;component/Icons/UserIcon.png"/>

Bizarre problem with WPF XAML file

I've just started a very simple WPF application which consists of a main large image and four smaller images.
In order to assist with the layout, I created some JPEGs in MsPaint containing the images -2, -1, 0, +1 and +2 and just copied them into the top level of the project directory.
The XAML segment contains, for the five images:
<Image Grid.Column="1" Grid.Row="2" Grid.ColumnSpan="4" Grid.RowSpan="1"
Margin="0,0,0,0" Name="imgPicture" Stretch="Fill" VerticalAlignment="Top"
Source="file:///C:/DAndS/Pax/MyDocs/VS2008/Projects/MyProj/zero.jpg" />
<Image Grid.Column="1" Grid.Row="4" Grid.ColumnSpan="1" Grid.RowSpan="1"
Margin="0,0,0,0" Name="imgPicMinus2" Stretch="Fill" VerticalAlignment="Top"
Source="file:///C:/DAndS/Pax/MyDocs/VS2008/Projects/MyProj/minus2.jpg" />
<Image Grid.Column="2" Grid.Row="4" Grid.ColumnSpan="1" Grid.RowSpan="1"
Margin="0,0,0,0" Name="imgPicMinus1" Stretch="Fill" VerticalAlignment="Top"
Source="file:///C:/DAndS/Pax/MyDocs/VS2008/Projects/MyProj/minus1.jpg" />
<Image Grid.Column="3" Grid.Row="4" Grid.ColumnSpan="1" Grid.RowSpan="1"
Margin="0,0,0,0" Name="imgPicPlus1" Stretch="Fill" VerticalAlignment="Top"
Source="file:///C:/DAndS/Pax/MyDocs/VS2008/Projects/MyProj/plus1.jpg" />
<Image Grid.Column="4" Grid.Row="4" Grid.ColumnSpan="1" Grid.RowSpan="1"
Margin="0,0,0,0" Name="imgPicPlus2" Stretch="Fill" VerticalAlignment="Top"
Source="file:///C:/DAndS/Pax/MyDocs/VS2008/Projects/MyProj/plus2.jpg" />
When I try to set the source property for the plus2 image, it complains with a dialog box stating:
Property value is not valid.
Details
|
V
The file plus2.jpg is not part of the project or
its 'Build Action' property is not set to 'Resource'.
Yet if I rename the file to plus3.jpg or plus2x.jpg, I don't have that problem.
Why is it complaining about plus2.jpg specifically?
Is it possible that you previously added then removed plus2.jpg?
Is it possible that you have not built the solution between the steps?
Clear src, build solution, set src to known working image, build solution, set src to non-working image.
Clear src of all images, build solution, set "Build Action" of all images to "None", build solution, set build-action to "Resource", build solution, set src of all images.
(Most Likely) Possible corrupted image, image with invalid color palette, image saved in invalid format.
See if you can load the image during run-time
Load image with Resouce Editor and "Save As".
The file extension does not make a difference, because the internal graphics format determines the image type. Meaning, if you created a jpg but saved it as bmp, the designer will still load the image correctly.
Try <Image.Source> <BitmapImage UriSource="sampleImages/bananas.jpg" /> </Image.Source>
I tried to duplicate the problem with no luck. I was able to use images that I "added existing" and images where I specified src="file:///c:..." Images inside the project, with and without the build-action set. Even images outside the project.
My other thought is there is something wrong with the image, but I did not add the comment. Yet, now that I think about it, the designer is going to try and load the image once you set src. If the image cannot be loaded then an exception will be thrown. Since you are in design-time, you get the invalid property prompt with an "obsure" details message.
What if you load the image during run-time to see what kind of exception is thrown, if any.
Don't really care about it. VS2008 when creating WPF applications has dozens of such warnings and most of them disappears after build. If app starts and is working - leave it alone. Personally I've installed around 10-15 hotfixes for various WPF related bugs in VS2008. VS2010 is much better.
Besides it's probably better to include image files in resources - you add them to the project (Add existing item) and then check whether the build action is set to Resource. (right click on that file in Solution Explorer and choose Properties)

Pack URI and path not resolving image in WPF

I have the following directory structure
Project
\Images
+view.png
control.xaml
and in the control I have a button defined by the following XAML:
<Button Click="Search"
Grid.Column="1"
Margin="0,5,5, 0"
HorizontalAlignment="Right">
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<Image Source="pack://application:,,,/images/view.png"
Width="16"
Height="16"
ToolTip="Search"
Cursor="Hand"
Opacity="0.8" />
</ControlTemplate>
</Button.Template>
</Button>
However, neither this pack URI method nor the "/images/view.png" is working. As I understand it, this is the same issue this question raises. However, I get the same error. The confusing thing is that in designer in Visual Studio 2008, the image renders correctly, but on the call to the InitializeComponent() call, I get:
Cannot convert string 'pack://application:,,,/images/view.png' in attribute 'Source' to object of type 'System.Windows.Media.ImageSource'. Cannot locate resource 'images/view.png'. Error at object 'System.Windows.Controls.ControlTemplate' in markup file 'RecapSpecEditControl;component/modaltreadgroupdatadialog.xaml' Line 61 Position 40.
I thought that maybe there was a namespace that I had to declare but according to the msdn site I believe I don't have to do anything like that.
I actually got this to work, but had to set my source to "/ProjectName;component/images/view.png" Because I have the ProjectName as a referenced assembly this is then the same as the Path: portion at the msdn page that I referenced in the question.
Set the Build Action for 'view.png' to Resource instead of Content and this problem should go away. I was able to reproduce your problem this way and it works correctly when set as a Resource.
Xaml.VB
Call the Image from Application folder and Design Page
Private Sub LoadImages()
Dim strUri As String
strUri = AppDomain.CurrentDomain.BaseDirectory() & "\NavigationImages\settingsicon.png"
Image2.Source = New BitmapImage(New Uri(strUri))
End Sub
Page load in Xaml.VB
Call LoadImages()
Xaml Design Page
Image Name="Image2"Height="32" HorizontalAlignment="Left"

Resources