我试图让我的主窗口在启动时记住并恢复位置和大小。所以我尝试将我的窗口的启动位置绑定到我的viewmodel中的属性,如下所示:
<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 和 其他信息:A&#39; Binding&#39 ;无法在“WindowStartupLocation”上设置&#39;属于MainWindow&#39;类型的财产。 A&#39;绑定&#39;只能在DependencyObject的DependencyProperty上设置。
我该如何纠正这个?
答案 0 :(得分:7)
尝试使用附加行为,以便绑定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
派生,也可以创建依赖属性,或者使用附加行为。
答案 1 :(得分:-2)
您无法绑定WindowsStartupLocation,此行会生成错误:
WindowStartupLocation="{Binding WindowStartupLocation}"
您可以将其设置为某个特定值,例如:
WindowStartupLocation="CenterScreen"