WPF只允许显示一个子窗体
WPF示例:
private TestFrm objFrm;
private void button_Click(object sender, RoutedEventArgs e)
{
if (historyFrm == null || historyFrm.IsVisible == false)
{
historyFrm = new HistoryFrm();
historyFrm.Show();
}
else if(historyFrm.WindowState == WindowState.Minimized)
{
historyFrm.WindowState = WindowState.Normal;
}
else
{
historyFrm.Activate();
}
}
WPF子窗体单例模式:
private static TestFrm _instance;
public static TestFrm Instance
{
get
{
if (ReferenceEquals(_instance, null))
{
_instance = new TestFrm();
}
return _instance;
}
}
调用:
TestFrm.Instance.Show();
另:
Winform示例:
private TestFrm objFrm;
private void button_Click(object sender, RoutedEventArgs e)
{
if (objFrm == null || objFrm.IsDisposed)
{
objFrm = new TestFrm();
objFrm.Show();
}
else
{
objFrm.Activate();
}
}
另外WPF示例:
WndNavigation _wnd = null; // WPF窗体全局变量
/// <summary>
/// 适用Show仅打开一个窗体,并显示在相对于主窗体的位置
/// </summary>
private void OpenWnd()
{
if (_wnd == null || !_wnd.IsLoaded)
{
_wnd = new WndNavigation();
_wnd.Closing += (s, e) => { _wnd = null; };
_wnd.WindowStartupLocation = WindowStartupLocation.Manual;
Window owner = System.Windows.Application.Current.MainWindow;
_wnd.Owner = owner;
if (owner != null)
{
#region 设置本窗体位置
System.Windows.Point pLeft = owner.PointToScreen(new System.Windows.Point(0, 0));
IntPtr hwnd = new WindowInteropHelper(owner).Handle;
HwndSource hwndSource = HwndSource.FromHwnd(hwnd);
if (hwndSource != null)
pLeft = hwndSource.CompositionTarget.TransformFromDevice.Transform(pLeft);
// 在主窗体右上角
//Point rightTop = new Point(pLeft.X + owner.ActualWidth, pLeft.Y);
//_wnd.Left = rightTop.X - _wnd.Width - 80;
//_wnd.Top = rightTop.Y + 25;
System.Windows.Point rightBottom = new System.Windows.Point(pLeft.X + owner.ActualWidth, pLeft.Y + owner.ActualHeight);
// 在主窗体右下角
_wnd.Left = rightBottom.X - _wnd.Width - 110;
_wnd.Top = rightBottom.Y - _wnd.Height - 70;
#endregion
}
else
{
_wnd.Left = SystemParameters.WorkArea.Width - 280;
_wnd.Top = SystemParameters.WorkArea.Height - 100;
}
}
_wnd.Topmost = true;
if (!_wnd.IsLoaded)
_wnd.Show();
else
_wnd.Activate();
}