0

I'm developing application with C#, Net 4.5.2 and WPF. It has remotely controlled GUI, so incoming HTTP GET requests (handled with Nancy) trigger some changes in Windows. Since server isn't running in GUI thread, I'm using Dispatcher.Invoke to call graphic changing methods. And there I get really weird behavior: if Show was not called for my Window, nothing happens. But calling Show creates 2 windows instead of one. How can I fix it?

public partial class App : Application //App.xaml.cs
{
    public static MainWindow mainWindow;

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        mainWindow = new MainWindow();
        //REMOVING NEXT LINE COMPLETELY BREAKS DISPATCHER.INVOKE IN mainWindow
        mainWindow.Show();
    }
}


public class MainModule : Nancy.NancyModule //Nancy server module
{
    public MainModule()
    {
        Get["/stop"] = param => App.mainWindow.StopContent();
    }
}


public partial class MainWindow : Window //WPF window
{

    public MainWindow()
    {
        InitializeComponent();
    }

    public void StopContent()
    {
        //LINE BELOW WON'T WORK IF Show WASN'T CALLED
        Dispatcher.Invoke(new Action(() => { Background = null; }));
    }
}
JustLogin
  • 1,822
  • 5
  • 28
  • 50
  • 1
    I also [had problems](https://stackoverflow.com/q/22460116/1997232) with creating windows in `Startup`. Second window is created probably because it's defined in `application.xaml` as `StartupUri="MainWindow.xaml"`. And `Invoke` won't work until you have window (something what will process dispatcher queue). See [other posts](https://stackoverflow.com/q/6708765/1997232) how to overcome it. – Sinatr Oct 04 '17 at 11:27
  • @Sinatr thanks, removing `StartupUri="MainWindow.xaml"` fixed double windows creation. But still, what's wrong with `Invoke` without `Show`? – JustLogin Oct 04 '17 at 11:38
  • If the window is not shown, what do you expect to happen if you set the background to null ? – Lumo Oct 04 '17 at 13:35
  • @Lumo even without calling `Show()` it's shown. – JustLogin Oct 04 '17 at 16:15
  • But then you're using StartupUri="MainWindow.xaml" right ? Otherwise there must be some other code that opens the window. I do exactly the same but it works. – Lumo Oct 05 '17 at 08:02
  • Yes, exactly. With `StartupUri="MainWindow.xaml"` window is shown, but `Invoke` do nothing. – JustLogin Oct 05 '17 at 10:54

0 Answers0