Question

This is the way I do it now, but I'm not sure if it's inefficient, since the runtime is O(n):

foreach (Window window in Application.Current.Windows)
{
    if (window.GetType() == typeof(TransactionsWindow))
    {
        this.Owner = window;
    }
}

Is there a way to make it constant or a more effective way than what I'm doing? Basically, I'm trying to confirm if I'm doing it the right way -- always trying to improve. The window gets opened by a button event, so I'm wondering if there's a way to find out which window the event was called from and assign that window as the owner, rather than having to search through all the open windows and hard coding the owner type.

Was it helpful?

Solution

This is fine. If you have enough windows open that O(N) here is an issue, your actual problem is much bigger than this loop.

That said, you might as well put a break; inside the if. Also, it would probably be better architecture for the windows doing theTransactionsWindow.Show() to also set theTransactionsWindow.Owner = this

OTHER TIPS

Instead of looping through windows, it might be a cleaner solution to use the Source property RoutedEventArgs variable in your button click event to find the actual button that made the call, and then the window owner of that button. Something like below:

private void Button_Click(object sender, RoutedEventArgs e)
    {
        Button btn = e.Source as Button;
        if (btn == null)
            return;

        Window parentWindow = Window.GetWindow(btn);
        this.Owner = parentWindow;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top