【发布时间】:2011-07-19 09:07:38
【问题描述】:
在 windows 窗体中,窗体的属性部分有一个选项,用于在应用程序设置和 windows 窗体之间建立绑定。
通常我会得到一个名为 frmMyFormName_Location 的设置,然后它会根据需要自动更新,我需要做的就是在应用程序退出时调用 Settings.Save() 方法来保存位置。
有人可以提供一个 WPF 中相同事情的示例吗,因为我无法弄清楚如何实现这一点?
【问题讨论】:
在 windows 窗体中,窗体的属性部分有一个选项,用于在应用程序设置和 windows 窗体之间建立绑定。
通常我会得到一个名为 frmMyFormName_Location 的设置,然后它会根据需要自动更新,我需要做的就是在应用程序退出时调用 Settings.Save() 方法来保存位置。
有人可以提供一个 WPF 中相同事情的示例吗,因为我无法弄清楚如何实现这一点?
【问题讨论】:
以下链接可能有助于存储应用程序设置。 WPF 窗口中没有一个名为 Location 的属性,但您确实有一个 LocationChanged 事件,您可以相应地处理和编写代码。
一个粗略的例子是:
private void Window_LocationChanged(object sender, EventArgs e)
{
var left = (double)GetValue(Window1.LeftProperty);
var top = (double)GetValue(Window1.TopProperty);
// persist these values
. . .
}
对于持久应用程序设置:
c# - approach for saving user settings in a WPF application? wpf 应用程序中的设置
【讨论】:
从 WPF 中的 .settings 文件绑定到用户或应用程序设置非常简单。
这是一个从设置中获取位置和大小的窗口示例:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:settings="clr-namespace:WpfApplication1.Properties"
Height="{Binding Height, Source={x:Static settings:Settings.Default}, Mode=TwoWay}"
Width="{Binding Width, Source={x:Static settings:Settings.Default}, Mode=TwoWay}"
Top="{Binding Top, Source={x:Static settings:Settings.Default}, Mode=TwoWay}"
Left="{Binding Left, Source={x:Static settings:Settings.Default}, Mode=TwoWay}">
<Grid>
</Grid>
</Window>
设置如下:
为了坚持,我只是使用以下代码:
void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
Properties.Settings.Default.Save();
}
【讨论】:
这是 WPF VB.NET 的示例
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
xmlns:Properties="clr-namespace:WpfApplication1"
Title="Test"
Loaded="Window_Loaded" Closing="Window_Closing"
Height="{Binding Height, Source={x:Static Properties:MySettings.Default}, Mode=TwoWay}"
Width="{Binding Width,Source={x:Static Properties:MySettings.Default}, Mode=TwoWay}"
Left="{Binding Left,Source={x:Static Properties:MySettings.Default}, Mode=TwoWay}"
Top="{Binding Top, Source={x:Static Properties:MySettings.Default}, Mode=TwoWay}"
>
<Grid Name="MainFormGrid"> ...
【讨论】: