ShowDialog() behind the parent window - wpf

I am using ShowDialog() with WindowStyle = WindowStyle.SingleBorderWindow; to open a modal window in my WPF (MVVM) application, but it lets me navigate to parent window using the Windows taskbar (Windows 7).
I've found an answer here: WPF and ShowDialog() but it isn't suitable for me because I don't need an "always on top" tool window.
Thanks in advance

Try setting the Owner property of the dialog. That should work.
Window dialog = new Window();
dialog.Owner = mainWindow;
dialog.ShowDialog();
Edit:
I had a similar problem using this with MVVM. You can solve this by using delegates.
public class MainWindowViewModel
{
public delegate void ShowDialogDelegate(string message);
public ShowDialogDelegate ShowDialogCallback;
public void Action()
{
// here you want to show the dialog
ShowDialogDelegate callback = ShowDialogCallback;
if(callback != null)
{
callback("Message");
}
}
}
public class MainWindow
{
public MainWindow()
{
// initialize the ViewModel
MainWindowViewModel viewModel = new MainWindowViewModel();
viewModel.ShowDialogCallback += ShowDialog;
DataContext = viewModel;
}
private void ShowDialog(string message)
{
// show the dialog
}
}

I had this problem but as the Window was being opened from a view model I didn't have a reference to the current window. To get round it I used this code:
var myWindow = new MyWindowType();
myWindow.Owner = Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive);
You can use: myWindow.Owner = Application.Current.MainWindow;
However, this method causes problems if you have three windows open like this:
MainWindow
|
-----> ChildWindow1
|
-----> ChildWindow2
Then setting ChildWindow2.Owner = Application.Current.MainWindow will set the owner of the window to be its grandparent window, not parent window.

When the parent window makes (and shows) the child window, that is where you need to set the owner.
public partial class MainWindow : Window
{
private void openChild()
{
ChildWindow child = new ChildWindow ();
child.Owner = this; // "this" is the parent
child.ShowDialog();
}
}
Aditionally, if you don't want an extra taskbar for all the children... then
<Window x:Class="ChildWindow"
ShowInTaskbar="False" >
</Window>

Much of the reason for the MVVM pattern is so that your interaction logic can be unit tested. For this reason, you should never directly open a window from the ViewModel, or you'll have dialogs popping up in the middle of your unit tests.
Instead, you should raise an event that the View will handle and open a dialog for you. For example, see this article on Interaction Requests: https://msdn.microsoft.com/en-us/library/gg405494(v=pandp.40).aspx#sec12

The problem seems to be related to Window.Owner, and indeed if you judge by previous knowledge that you might have of the Win32 API and WinForms, a missing owner would be the typical cause of such a problem, but as many have pointed out, in the case of WPF that's not it. Microsoft keeps changing things to keep things interesting.
In WPF you can have a dialog with a specific owner and you can still have the dialog appear in the taskbar. Because why not. And that's the default behavior. Because why not. Their rationale is that modal dialogs are not kosher anymore, so you should not be using them; you should be using modeless dialogs, which make sense to show as separate taskbar icons, and in any case the user can then decide whether they want to see different app windows as separate icons, or whether they want to see them grouped.
So, they are trying to enforce this policy with complete disregard to anyone who might want to go against their guidelines and create a modal dialog. So, they force you to explicitly state that you do not want a taskbar icon to appear for your dialog.
To fix this problem, do the following in the constructor of your view class:
ShowInTaskbar = false;
(This may happen right after InitializeComponent();
This is equivalent to Xcalibur37's answer, though the way I figure things, since WPF forces you to have both a .cs file and a .xaml file, you might as well put things that are unlikely to change in the .cs file.

Add "ShowInTaskbar" and set it to false.

Even if this post is a bit old, I hope it is OK that I post my solution.
All the above results are known to me and did not exactly yield the desired result.
I am doing it for the other googlers :)
Lets say f2 is your window that you want to display on top of f1 :
f2.Owner = Window.GetWindow(this);
f2.ShowDialog();
That's it , I promise it will not disappear !
HTH
Guy

Related

Caliburn.Micro - why uses UserControl instead of Window

My question is exactly like in the title.
I'm starting with Caliburn.Micro for MVVM approach (which also is new for me) and in every tutorial the first step is to remove the default MainWindow.xaml file and create a new UserControl file. Why is that? UserControl does not even accept a Title. Isn't it possible to build application using normal Windows? I already tried that, but with every launch I get error "Cannot find view for ViewModel", although both MainView.xaml and MainViewModel.cs are present. When I created a pair of USerControl and ViewModel for it, everything started to work as expected. So again, why Windows don't work?
It wouldn't really be a problem, but I'm thinking that some additions like Modern UI themes for WPF might not work without a window. I'm not sure of that.
Probably one solution would be to display a defined UserControl View inside of a Window, but it's just a workaround.
You could create your own custom shell window by creating a custom WindowManager:
public class CustomWindowManager : WindowManager
{
protected override Window CreateWindow(object rootModel, bool isDialog, object context, IDictionary<string, object> settings)
{
Window window = new Window();
window.Title = "custom...";
return window;
}
}
...that you register in your bootstrapper:
public class HelloBootstrapper : BootstrapperBase
{
...
protected override void Configure()
{
_container.Singleton<IWindowManager, CustomWindowManager>();
...
}
}

WPF best practice to get current MainWindow instance?

I got a warning that this may be a subjective question and might be closed, but I'm going to ask anyway.
I'm basically trying to access a button on my MainWindow in a WPF application from a UserControl that gets loaded up from within the MainWindow.
I'm currently accessing it like this from the UserControl's code behind:
((MainWindow)Application.Current.MainWindow).btnNext
But it does look messy, and from what I've read is not considered a best practice. Anyone able to provide an answer that constitutes a best practice for Accessing controls / properties from the current instance of a MainWindow - or any other active windows / views for that matter?
You can get a reference to the parent window of the UserControl using the Window.GetWindow method. Call this once the UserControl has been loaded:
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
this.Loaded += (s, e) =>
{
MainWindow parentWindow = Window.GetWindow(this) as MainWindow;
if (parentWindow != null)
{
//...
}
};
}
}
You could also access all open windows using the Application.Current.Windows property:
MainWindow mainWindow = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
Which one to use depends on your requirements. If you want a reference to the application's main window for some reason, you could stick with your current approach. If you want a reference to the parent window of the UserControl, using the Window.GetWindow method would be better.
The best practice is generally to use the MVVM design pattern and bind UI controls to source properties of a view model that may be shared by several views. But that's another story. You could refer to the following link for more information about the MVVM pattern: https://msdn.microsoft.com/en-us/library/hh848246.aspx

Open new form and hide this form in mvvm light toolkit

I have a LoginWindows, that run in startup.
I have a enterButton ,when click it, send a parametr to mainwindows and show it then hide self.
public RelayCommand EnterCommand { get; set; }
...
public LoginViewModel()
{
EnterCommand = new RelayCommand(() => Enter());
}
private object Enter()
{
//Show MainWndow
}
What is the best way to open a new window from the viewmodel in mvvmLight?
It is Useful answer. https://stackoverflow.com/a/16994523/970404
Concepts:
Registering Multiple VM's with the SimpleIoC and using
GetInstance(...) to request them out.
Messenger class usage with a custom message type OpenWindowMessage
Opening Modal / Non Modal
Windows from a parent VM staying true to the MVVM principles
Passing
data between windows(just shown in NonModal)
Important Note:
The method used in this example to set the non DP DialogResult from the modal window is not MVVM friendly cos it uses code-behind to set the DialogResult property on a Window.Closing event which should be avoided(If needing to be "testable"). My preferred approach is a bit long and is very well documented HERE(Mixture of question and answer). Hence why I ignored it for the sake of this sample.

Open a window after the mainWindow and activate it

In my application is required the user to select an item from a list before continues uses the application.
To do this, I have a window with the desired items and I display it when the MainWindow displays.
public MainWindow()
{
InitializeComponent();
var itemsWindow = new ItemsWindow();
itemsWindow.Show();
}
The problem is that the window opens in background. How can I open the window in foreground?
The preferable would be to open the itemsWindow on applications start up and onClose event of itemsWindow to display the mainWindow, but I think this approach is far away from my knowledge. Nevertheless, I would appreciate it if someone could post something for how to achieve this.
Thanks
Use ShowDialog() method instead. That way, you won't have to worry about activating that window and user won't be able to interact with MainWindow until ItemsWindow has been closed.
Example:
var itemsWindow = new ItemsWindow();
itemsWindow.ShowDialog();

WPF custom control question

i've done this before but i cannot find my old code.
how do you embed a window inside a window.
let say i created a custom form and saved it as Window1.xaml, and want to embed it in Window2.xaml, without copy and pasting the xaml code.. TIA
EDIT: i think my question is somewhat misleading, i'll rephrase it.
i have this Window1.xaml i added custom headers and background images/colors.
then in Window2.xaml, i want Window1 to be a custom control and embed it here.
not sure if its Content Presenters, still googling for the answer :)
You can't host a WPF Window inside another WPF Window, but you could move the content from one Window to another:
var window1 = new Window1();
var window2 = new Window2();
var content = window1.Content;
window1.Content = null;
window2.Content = content;
Note that you set window1.Content to null or else you get an exception, since the content will have a visual parent otherwise.
UPDATE
It appears all you need to do is to copy all the XAML between the <Window></Window> tags in Window1 into a new UserControl, then host that user control in Window2.
I believe you should make use of Pages or usercontrols in such cases. This way you can navigate to other parts/pages/controls defined in application. CodeKaizen is right , you can't host a window inside another window
I'm not sure you can do that - however, you shouldn't put the user interface directly into a window, use a normal control (either custom or user) instead and reuse that in your windows.
I know you can do it in code behind
//Window you want to show
Window1 child = new Window1();
object content = child.Content;
child.Content = null;
//Where to show
this.grid1.Children.Clear();
this.grid1.Children.Add((UIElement)content);
Hope helps!
It sounds like you really want a UserControl. Change Window1's type from Window to UserControl and then put that UserControl in Window2.

Resources