Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF hosted in WPF and how can i change control in MainWindow UI from wcf?

I write WCF code and hosted in my WPF app. I write class to switch my MainWindow to show other page in my project

public static class Switcher
    {
        public static MainWindow pageSwitcher;

        public static void Switch(Page newPage)
        {
            pageSwitcher.Navigate(newPage);
        }       
    }

and I write my wcf service like this:

[ServiceContract]
    public interface IAppManager
    {
        [OperationContract]
        void DoWork();
        [OperationContract]
        void Page1();
        [OperationContract]
        void Page2();
    }
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class AppManager : IAppManager
    {

        public void DoWork()
        {
        }
        public void Page1()
        {
            MainWindow.pageSwitcher = new MainWindow();
            MainWindow.Switch(new Page1());
        }
        public void Page2()
        {
            MainWindow.pageSwitcher = new MainWindow();
            MainWindow.Switch(new Page2());
        }
    }

I want change page remotely from another computer with WCF but it not work and I trace code the wcf is run and response but do not do anything how can access to main thread to change ui page or other element?

like image 926
Faraz Avatar asked Sep 29 '22 04:09

Faraz


2 Answers

Your current solution is unusual, but WCF can be hosted in a WPF application. However you should never try to directly manipulate the UI from the WCF service - you'll have cross thread issues to begin with.

What you should consider doing is using messaging via a pub-sub broker (image linked from MSDN):

enter image description here

Something that fits this bill nicely is Prism's EventAggregator. A couple of samples I cherry picked are Simplifying PRISM’s EventAggregator and Prism EventAggregator Sample.

The way you use this is the service registers events and then raises them, the WPF subscribes to those events and processes them. With this you can also specify whether to receive the events on the UI thread or a background thread.

like image 115
slugster Avatar answered Oct 06 '22 20:10

slugster


I suggest you start over and this time separate the WCF from your WPF app.

You need to:

1) Separate WCF from WPF - should be in different layers.

2) Use WCF with duplex binding - this way your WCF service will be able to communicate with clients when it needs to.

3) In your WCF callback contract (implemented by the client) - you should prepare a method that will be used to change the local UI mode.

Duplex binding is the perfect solution for your needs.

You can reed about Duplex here

Hope I helped! Eking.

like image 44
Eking Avatar answered Oct 06 '22 20:10

Eking