Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

WPF Button Image

Posted on 2010-08-17
8
1,053 Views
Last Modified: 2013-11-12
I wish to load images to button controls in a WPF application at run time. Based on application scenario, I wish to know how to change the button image.

I know the static way of loading images, but I need inputs on how to load it dynamically.
0
Comment
Question by:narayanan_mahalingam
  • 3
  • 3
  • 2
8 Comments
 
LVL 63

Expert Comment

by:Fernando Soto
ID: 33460371
Hi narayanan_mahalingam;

You can do that as shown in the code snippet below.

Fernando
// Create the image element.
Image simpleImage = new Image();

// Create source.
BitmapImage bi = new BitmapImage();
// BitmapImage.UriSource must be in a BeginInit/EndInit block.
bi.BeginInit();
// The first parameter of Uri is the location of the image on disk
bi.UriSource = new Uri(@"D:\Temp\Photo.jpg", UriKind.RelativeOrAbsolute);
bi.EndInit();
// Set the image source.
simpleImage.Source = bi;

// Assuming that the button name is button1 
button1.Content = simpleImage;

Open in new window

0
 
LVL 10

Expert Comment

by:k_swapnil
ID: 33461506
Hi Narayan,

Please have a look at the code below...
I have used binding and INotifyPropertyChanged Interface for the solution.

For the sample purposes I have used the code behind as the DataContext for the xaml file but you can replace it as per your needs.

Thx!
Swaps....
///WINDOW2.XAML

<Window x:Class="WpfApplication1.Window2"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window2" Height="300" Width="300">
    <StackPanel>
      <Button Width="150" Height="50" Margin="10">
            <Image Source="{Binding ScenarioImage}"/>
      </Button>
        <ComboBox Margin="20" Height="27" Width="209" SelectionChanged="ComboBox_SelectionChanged">
            <ComboBoxItem>Scenario 1</ComboBoxItem>
            <ComboBoxItem>Scenario 2</ComboBoxItem>
            <ComboBoxItem>Scenario 3</ComboBoxItem>
        </ComboBox>
    </StackPanel>
</Window>

=======================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for Window2.xaml
    /// </summary>
    public partial class Window2 : Window, INotifyPropertyChanged
    {
        private BitmapImage _scenarioImage;
        public BitmapImage ScenarioImage
        {
            get
            {
                return _scenarioImage;
            }
            set
            {
                _scenarioImage = value;
                OnPropertyChanged("ScenarioImage");
            }
        }

        public Window2()
        {
            InitializeComponent();
            ScenarioImage = new BitmapImage(new Uri(@"..\Resources\folder.png", UriKind.Relative));
            this.DataContext = this;
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox cmb = sender as ComboBox;
            if (cmb.SelectedIndex == 0) // senario - 1
            {
                ScenarioImage = new BitmapImage(new Uri(@"..\Resources\folder.png", UriKind.Relative));
            }
            if (cmb.SelectedIndex == 1) // senario - 2
            {
                ScenarioImage = new BitmapImage(new Uri(@"..\Resources\wmpnss_bw48.png", UriKind.Relative));
            }
            if (cmb.SelectedIndex == 2) // senario - 3
            {
                ScenarioImage = new BitmapImage(new Uri(@"..\Resources\wmpnss_color48.png", UriKind.Relative));
            }
        }

        #region INotifyPropertyChanged Members

        /// <summary>
        /// Property Changed Event Handler
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Property Changed Event Handler
        /// </summary>
        /// <param name="name">name of property</param>
        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }

        #endregion
    }
}

Open in new window

0
 

Author Comment

by:narayanan_mahalingam
ID: 33466542
Swapnil
I am not able to get your code working wi th the relative Uri. Only when I hardcode the complete path for the BitmapImage constructor does the image load.
I have added the folder with the images into the project. What else am I  missing in making in the relative Uri work?
narayanan
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 10

Accepted Solution

by:
k_swapnil earned 250 total points
ID: 33466854
its the relative path from the exe...

For eg my exe is in SampleProject\Debug folder and images are SampleProject\Resources folder, so the relative path is ..\Resources\xyz.png.

"..\" is used to come out of the folder.

Hope this helps...if not please let me know your folder structure (full paths of the directories) i.e where exe is present and where images are present

Thx!
Swaps...
0
 

Author Comment

by:narayanan_mahalingam
ID: 33466931
Swaps
My exe is in the following location
MyProject\bin\Debug\*.exe

I have put the images in the following folder and added into the project.

MyProject\Images\*.png

I gave the relative Uri as new Uri(@"../../Images/folder.png", UriKind.Relative). This does not work.

Hope my uri path is right..
0
 
LVL 10

Expert Comment

by:k_swapnil
ID: 33472110
Have you added the images into project resources?

Thx!
Swaps...
1.JPG
0
 
LVL 63

Expert Comment

by:Fernando Soto
ID: 33475315
Hi Swaps;

So you don't like the very first solution?

Fernando
0
 

Author Comment

by:narayanan_mahalingam
ID: 33477747
Swapnil

I added the resources thru the Project Properties as per your suggestion. Still, the images do not show up in the button.
I am using VC# 2010 Express.
Is there anything I can look for in the debug window to check for the path correctness?
Narayanan
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Asp.net Form view Pager Template First Record 2 82
ODBC Connection; Switch between 2 SQL Databases VBA 11 103
Windows Process running 3 58
Recommendation vb6 to vb.net or others 14 174
This article describes how to programmatically preset the "Pages per Sheet" option that's available with most printer drivers.   This setting lets you do "n-Up" printing, where two, four, or more pages are printed on each sheet of paper. If your …
For most people, the WrapPanel seems like a magic when they switch from WinForms to WPF. Most of us will think that the code that is used to write a control like that would be difficult. However, most of the work is done by the WPF engine, and the W…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…

790 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question