如何使用 xaml 将 WPF 应用程序窗口启动位置设置到右上角?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12590336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set WPF application windowstartuplocation to top right corner using xaml?
提问by vish213
I just want to set windowstartuplocation to top right corner of desktop. Now to clear some things up, I saw this thread with same question:
我只想将 windowstartuplocation 设置为桌面的右上角。现在要澄清一些事情,我看到这个帖子有同样的问题:
Changing the start up location of a WPF window
Now I don't want to get confused to what they are referring as right or left, I want my application to start in top right corner,where right refers to MY RIGHT SIDE(not as if my desktop is a person looking at me and ITS RIGHT SIDE).So,
现在我不想对他们所指的右侧或左侧感到困惑,我希望我的应用程序从右上角开始,其中右侧指的是我的右侧(不像我的桌面是一个人看着我和它的右侧)。所以,
1.)setting left and top to 0 only is not a solution(brings app to left side not right)
1.) 仅将 left 和 top 设置为 0 不是解决方案(将应用程序带到左侧而不是右侧)
2.)I tried using SystemParameters.PrimaryScreenWidth, but I can't perform operation to subtract the width of my app from this value at binding time.
2.) 我尝试使用 SystemParameters.PrimaryScreenWidth,但我无法在绑定时执行操作以从该值中减去我的应用程序的宽度。
Is there a way I can do it without going into much complexity?
有没有一种方法可以在不复杂的情况下做到这一点?
回答by Reed Copsey
Is there a way I can do it without going into much complexity?
有没有一种方法可以在不复杂的情况下做到这一点?
The simplest way would be to setup your start location manually, and then set the Left
property in code behind:
最简单的方法是手动设置起始位置,然后Left
在后面的代码中设置属性:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1"
Height="500" Width="500"
WindowStartupLocation="Manual"
Top="0">
</Window>
In your code behind:
在你后面的代码中:
public Window1()
{
InitializeComponent();
this.Left = SystemParameters.PrimaryScreenWidth - this.Width;
}
This is one place where I feel the simplicity of doing it in code outweights any disadvantages of introducing code behind.
这是一个我觉得在代码中做这件事的简单性胜过在后面引入代码的任何缺点的地方。
回答by Josh
By using WorkArea.Width make sure the width of the taskbar is taken into account (when placed on a side, left or right). By using this.Width or this.MaxWidth make sure your window never slips outside the work area, but both require their value be set (in xaml or in code behind) to not produce the value NaN (Not a Number) for this.Left.
通过使用 WorkArea.Width 确保将任务栏的宽度考虑在内(放置在一侧、左侧或右侧时)。通过使用 this.Width 或 this.MaxWidth 确保您的窗口永远不会滑出工作区,但两者都需要设置它们的值(在 xaml 或后面的代码中)以不为 this.Left 生成值 NaN(非数字) .
public MainWindow()
{
InitializeComponent();
this.Left = SystemParameters.WorkArea.Width - this.MaxWidth;
}
<Window
... more code here ...
WindowStartupLocation="Manual" Top="0" MaxWidth="500" >