我正在尝试让我的主窗口记住并恢复启动时的位置和大小.所以我尝试将我的窗口的启动位置绑定到我的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"
...>
Run Code Online (Sandbox Code Playgroud)
我的viewmodel:
...
// 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;
}
...
Run Code Online (Sandbox Code Playgroud)
当我运行应用程序时,我得到一个System.Windows.Markup.XamlParseException和附加信息:无法在'MainWindow'类型的'WindowStartupLocation'属性上设置'绑定'.'绑定'只能在DependencyObject的DependencyProperty上设置.
我该怎么纠正这个?
尝试使用附加行为来绑定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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
<Window
PropertiesExtension:WindowExt.WindowStartupLocation="{Binding ..}" />
Run Code Online (Sandbox Code Playgroud)
正如错误所述,WindowStartupLocation
不是依赖性,这意味着你无法绑定它.解决方案可以是派生自Window
,也可以创建依赖属性,或者使用附加行为.
归档时间: |
|
查看次数: |
864 次 |
最近记录: |