2013-06-19 178 views
2

我有一個應用程序在第二個屏幕上運行,當用戶在第一個屏幕上運行應用程序時,應用程序檢測到第二個顯示器並將其位置更改爲第二個屏幕。wpf窗口位置問題

這有一個問題,主窗口的子項出現在第一個顯示器中。如果所有者屬性正確建立,則不應該發生這種情況。

Window1 w = new Window1(); 
win.Owner = Application.Current.MainWindow; 

我的應用程序很複雜,它由調用子窗口的組件組成,但我附上了一段代碼來說明問題。 。在執行第一個監視器的代碼,在窗口中手動移動到輔助監視器,然後按下按鈕來調用子窗口這就是出現在第一個顯示器:(

注意:我知道,我可以寫一個代碼,檢測各子窗口輔助監視器,並移動到那時,不過我想一個解決方案更加簡單,正確,如果有可能

注2:運行Visual Studio的外部應用程序,從「.EXE」直接。在Visual Studio中工作正常。

<Window x:Class="Test.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:Control="clr-namespace:Borrarrrrr" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <Control:UserControl1 x:Name="ctr" /> 
    </Grid> 
</Window> 

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

    private void Button_Click(object sender, RoutedEventArgs e) 
    { 
     Window1 w = new Window1(); 
     //w.Owner = this; 
     w.Owner = Application.Current.MainWindow; 
     w.Show(); 
    } 
} 


<UserControl x:Class="Test.UserControl1" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"> 
    <Grid> 
     <Button Click="Button_Click"></Button> 
    </Grid> 
</UserControl> 

    public partial class UserControl1 : UserControl 
    { 
     public UserControl1() 
     { 
      InitializeComponent(); 
     } 

     private void Button_Click(object sender, RoutedEventArgs e) 
     { 
      Window1 w = new Window1(); 
      w.Owner = Application.Current.MainWindow; 
      w.Show(); 
     } 
    } 


<Window x:Class="Test.Window1" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="Window1" Height="300" Width="300" 
     WindowStartupLocation="CenterOwner" WindowStyle="None" AllowsTransparency="True" 
     WindowState="Maximized"> 
    <Grid Background="Aqua"> 

    </Grid> 
</Window> 
+0

任何響應??? – Keniako

回答

3

嘗試設置Window.WindowStartupLocation

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    Window1 w = new Window1(); 
    w.Owner = Application.Current.MainWindow; 
    w.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner; 
    w.Show(); 
} 
+0

在一個MDI應用程序,其中不僅主窗口可能會產生新的窗口,它可能更可取用'w.Owner = this;' –

+0

感謝您的迴應,顯然這是行不通的。中心擁有者的財產已經在XAML中建立。 WindowStartupLocation = 「CenterOwner」。我鼓勵你使用代碼,我認爲有一個WPF錯誤。 – Keniako

+0

設置子窗口的'WindowStartupLocation'後,行爲是否有任何改變?設置這對我來說達到了所需的結果。 – StaWho