Search code examples
c#asp.netwpfclassclass-instance-variables

C# display image in WPF from a custom class other than MainWindow : Window


Hello I have a simple WPF window and I want to load and display a logo image on specific "Image" item. The following code works perfectly and I can display the logo.

namespace WPFexample
{
    public partial class MainWindow : Window
    { 
        public MainWindow()
        {
            InitializeComponent();
            var uri = new Uri("pack://application:,,,/Assets/Logo.png");
            LogoImage.Source = new BitmapImage(uri);
        }
    }
}

Now I want to create another class which can access the GUI and display from there the logo:

namespace WPFexample
{
    public partial class MainWindow : Window
    { 
        public MainWindow()
        {
            InitializeComponent();                
        }
    }

    class MyClass
    {
        private void myCustomDisplay()
        {
            var uri = new Uri("pack://application:,,,/Assets/Logo.png");
            // How can I call the LogoImage.Source from this place??
        }
    }
}

Initially I thought that I could do this but nothing happened:

class MyClass
{   
    private void myCustomDisplay()
    {
        MainWindow MainWindowClassRef = new MainWindow();
        var uri = new Uri("pack://application:,,,/Assets/Logo.png");
        MainWindowClassRef.LogoImage.Source = new BitmapImage(uri);
    }
}

Any suggestion why I cannot display it?

This does not work either:

namespace WPFexample
{
    public partial class MainWindow : Window
    { 
        public MainWindow()
        {
            InitializeComponent();                
        }
        public void DisplayInGUI()
        {
            var uri = new Uri("pack://application:,,,/Assets/ITLLogo.png");
            LogoImage.Source = new BitmapImage(uri);            
        }
    }

    class MyClass:MainWindow 
    {
        public void myCustomDisplay()
        {
            DisplayInGUI()
        }
    }
}

Solution

  • To access a member (e.g. property or method) of the MainWindow instance, you can cast the MainWindow property of the current Application instance to your MainWindow class.

    So e.g. call the MainWindow's DisplayInGUI() method by

    ((MainWindow)Application.Current.MainWindow).DisplayInGUI();
    

    You probably want to pass the actual logo image as parameter to a method like

    public partial class MainWindow : Window
    { 
        ...
        public void SetLogoImage(ImageSource image)
        {
            LogoImage.Source = image;
        }
    }
    

    and call it like this:

    ((MainWindow)Application.Current.MainWindow).SetLogoImage(
        new BitmapImage(new Uri("pack://application:,,,/Assets/ITLLogo.png")));
    

    EDIT: Call the method from another thread like this:

    var mainWindow = (MainWindow)Application.Current.MainWindow;
    mainWindow.Dispatcher.Invoke(() => mainWindow.DisplayInGUI());