July 1, 2010

Using Images in WPF

Using project resources in WPF
  1. Create sub-directory for resources called say "Resources"
  2. Add your resources (images, icons etc.) to it.
  3. Copy the folder structure into the VS project and add the resource files to it.
  4. Check the Properties of your resources in VS project file to ensure they have a Build Action of 'Resource'
Creating an image in WPF: In XAML:
<Image Source="Resources/P4.ico" />
Adding an image to a window's resources is very easy:
        <Image x:Key="P4Icon" Source="Resources/P4.ico" />
In code:
Image myImage = new Image();
myImage.Source = new BitmapImage(new Uri("Icons/MyImage.png", UriKind.Relative));
Inserting an image in a button is very easy in WPF:
<Button HorizontalAlignment="Left" Margin="5,8,0,10" Name="p4But" Width="34" Click="p4But_Click">
   <Image Source="Resources/P4.ico" Width="24" />

No comments: