解决WPF弹出子窗体如何设置停靠在主窗体的边缘

窗体代码

思路获取主窗体的位置坐标,根据主窗体的位置坐标和长宽尺寸计算子窗体的实际位置,并赋值给子窗体的Top和Left属性。

public partial class PromptDialogBox : Window
{ 
    /// <summary>
   ///     关闭计时器
   /// </summary>
    private DispatcherTimer _timerClose;
    private int _waitTime = 2;

    /// <summary>
    ///     计数
    /// </summary>
    private int _tickCount;
    public PromptDialogBox()
    {
        InitializeComponent();
        StartTimer();
    }

    public void PrompShow()
    {
        this.Owner = ApplicationInfo.ParentWindow;
        this.Top=Owner.Top;
        this.Left=Owner.Left+ Owner.ActualWidth-this.Width;
        this.Show();
    }
    /// <summary>
    ///     开始计时器
    /// </summary>
    private void StartTimer()
    {
        _timerClose = new DispatcherTimer
        {
            Interval = TimeSpan.FromSeconds(1)
        };
        _timerClose.Tick += delegate
        {
            if (IsMouseOver)
            {
                _tickCount = 0;
                return;
            }

            _tickCount++;
            if (_tickCount >= _waitTime)
            {
                this.Close();
            }
        };
        _timerClose.Start();
    }
}

然而按照以上方式设置,并没有达到理想效果,子窗体的位置看着没有什么规律。

网上找了资料(通过设置WindowStartupLocation.Manual),这样我们可以自由设置它的位置。

于是在上面构造函数中加入一行

 public PromptDialogBox()
 {
     InitializeComponent();
     this.WindowStartupLocation = WindowStartupLocation.Manual;
     StartTimer();
 }

果然达到相要的效果了。

posted @ 2024-12-27 09:56  follow_discoverer  阅读(81)  评论(0)    收藏  举报