在 Windows Forms 中,表单属性部分有一个选项,可以建立应用程序设置与 Windows Form 之间的绑定。通常我会得到一个名为 frmMyFormName_Location 的设置,这个设置会在需要时自动更新,而我只需要在应用程序退出时调用 Settings.Save() 方法来保存位置即可。
请问是否能提供一个在 WPF 中实现同样功能的示例?我一直无法弄清楚如何完成此操作。
请问是否能提供一个在 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"> ...
private void Window_LocationChanged(object sender, EventArgs e)
{
var left = (double)GetValue(Window1.LeftProperty);
var top = (double)GetValue(Window1.TopProperty);
// persist these values
. . .
}
为持久化应用程序设置:
C# - 在 WPF 应用程序中保存用户设置的方法? settings-in-a-wpf-application