[英]WPF Window set custom startup location/position within main screen
我有一個用 wpf 完成的自定義消息框。
自定義消息框視圖 xaml :
<Window x:Class="My.XAML.Controls.Windows.WpfMessageBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WpfMessageBox" MinHeight="160"
MinWidth="420" MaxHeight="750" MaxWidth="750"
Background="Transparent"
SizeToContent="WidthAndHeight"
WindowStartupLocation="CenterScreen"
ShowInTaskbar="False" ResizeMode="NoResize"
WindowStyle="None" Topmost="True">
</Window>
在我的主窗口中,當用戶單擊按鈕時,我會顯示此自定義 wpf 消息框窗口,作為單擊按鈕時調用的示例:
var messageBoxResult = WpfMessageBox.Show("Title", "MyMessage",
MessageBoxButton.YesNo, WpfMessageBox.MessageBoxImage.Warning);
if (messageBoxResult != MessageBoxResult.Yes) return;
*自定義消息框代碼隱藏 xaml.cs:
public partial class WpfMessageBox : Window
{
private WpfMessageBox()
{
InitializeComponent();
}
public static MessageBoxResult Show(string caption, string text, MessageBoxButton button, MessageBoxImage image, EnumLocation location)
{
switch (location)
{
case EnumLocation.TopLeft:
// Locates at top left
break;
case EnumLocation.TopCenter:
// Locates at top center
break;
case EnumLocation.TopRight:
// Locates at top right
break;
// and so on with the rest of cases: middle left, middle center, middle right, bottom left, bottom center and bottom right.
}
}
}
默認情況下,此自定義消息框在主屏幕的中心打開。
我現在想要做的是將參數(枚舉)傳遞給我的 WpfMessageBox.Show 方法,以指示我的自定義消息框我希望它位於主屏幕中的哪個位置。 參數將是這些:
我怎樣才能做到這一點?
我怎樣才能做到這一點?
將窗口的WindowStartupLocation
屬性設置為Manual
,然后設置窗口的Left
和Top
屬性以確定其初始位置。
//top-left:
WindowStartupLocation = WindowStartupLocation.Manual;
Left = 0;
Top = 0;
您需要計算要使用的值,例如使用SystemParameters.PrimaryScreenWidth
和SystemParameters.PrimaryScreenHeight
屬性。
在 xaml 中設置 Manual 后,您轉到 c# 並相應地設置位置。
// "TL", "TR", "BL", "BR" };
switch (position)
{
case "TL":
{
this.Left = 0;
this.Top = 0;
break;
}
case "TR":
{
this.Left = SystemParameters.PrimaryScreenWidth - this.Width;
this.Top = 0;
break;
}
case "BL":
{
this.Left = 0;
this.Top = SystemParameters.WorkArea.Height - Height;
break;
}
case "BR":
{
this.Left = SystemParameters.WorkArea.Width - Width;
this.Top = SystemParameters.WorkArea.Height - Height;
break;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.