绑定窗口启动位置
本文关键字:位置 启动 窗口 绑定 | 更新日期: 2023-09-27 18:34:48
>我正在尝试使我的主窗口记住并在启动时恢复位置和大小。因此,我尝试将窗口的启动位置绑定到视图模型中的属性,如下所示:
<Window x:Class="MyApp.Views.MainWindow"
...
Width="{Binding Width}"
Height="{Binding Height}"
WindowStartupLocation="{Binding WindowStartupLocation}"
WindowState="{Binding WindowState}"
MinHeight="600"
MinWidth="800"
Closing="OnWindowClosing"
Closed="OnWindowClosed"
ContentRendered="OnMainWindowReady"
...>
我的视图模型:
...
// Default settings
WindowState = (WindowState)FormWindowState.Normal;
this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
Width = 800;
Height = 600;
// check if the saved bounds are nonzero and is visible on any screen
if (Properties.Settings.Default.WindowStartupLocation != Rectangle.Empty &&
IsVisibleOnAnyScreen(Properties.Settings.Default.WindowStartupLocation))
{
this.WindowStartupLocation = WindowStartupLocation.Manual;
this.WindowState = (WindowState)Properties.Settings.Default.WindowState;
Height = Properties.Settings.Default.WindowStartupLocation.Size.Height;
Width = Properties.Settings.Default.WindowStartupLocation.Size.Width;
Left = Properties.Settings.Default.WindowStartupLocation.Left;
Top = Properties.Settings.Default.WindowStartupLocation.Top;
}
...
当我运行应用程序时,我得到一个System.Windows.Markup.XamlParseException和其他信息:不能在类型为"MainWindow"的"WindowStartupLocation"属性上设置"绑定"。"绑定"只能在依赖对象的依赖属性上设置。
我应该如何纠正?
尝试使用允许您绑定 WindowStartupLocation
属性的附加行为:
namespace YourProject.PropertiesExtension
{
public static class WindowExt
{
public static readonly DependencyProperty WindowStartupLocationProperty;
public static void SetWindowStartupLocation(DependencyObject DepObject, WindowStartupLocation value)
{
DepObject.SetValue(WindowStartupLocationProperty, value);
}
public static WindowStartupLocation GetWindowStartupLocation(DependencyObject DepObject)
{
return (WindowStartupLocation)DepObject.GetValue(WindowStartupLocationProperty);
}
static WindowExt()
{
WindowStartupLocationProperty = DependencyProperty.RegisterAttached("WindowStartupLocation",
typeof(WindowStartupLocation),
typeof(WindowExt),
new UIPropertyMetadata(WindowStartupLocation.Manual, OnWindowStartupLocationChanged));
}
private static void OnWindowStartupLocationChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
Window window = sender as Window;
if (window != null)
{
window.WindowStartupLocation = GetWindowStartupLocation(window);
}
}
}
}
用法:
<Window
PropertiesExtension:WindowExt.WindowStartupLocation="{Binding ..}" />
正如错误所述,WindowStartupLocation
不是依赖项,这意味着您无法绑定它。解决方案可以是派生自 Window
并创建依赖项属性,也可以使用附加行为。
您不能绑定 WindowsStartupLocation,此行将生成错误:
WindowStartupLocation="{Binding WindowStartupLocation}"
您可以将其设置为某个特定值,如下所示:
WindowStartupLocation="CenterScreen"