WPF窗口位置绑定

4
在 Windows Forms 中,表单属性部分有一个选项,可以建立应用程序设置与 Windows Form 之间的绑定。通常我会得到一个名为 frmMyFormName_Location 的设置,这个设置会在需要时自动更新,而我只需要在应用程序退出时调用 Settings.Save() 方法来保存位置即可。
请问是否能提供一个在 WPF 中实现同样功能的示例?我一直无法弄清楚如何完成此操作。
3个回答

20

在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();
}

也适用于WindowsState(正常,最小化,最大化)。使用PresentationFramework中的枚举:System.Windows.WindowState。 - Welcor

1

这里是一个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"> ...

0
以下链接可能有助于存储应用程序设置。 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# - 在 WPF 应用程序中保存用户设置的方法? settings-in-a-wpf-application

WPF 应用程序设置文件

存储常见应用程序设置的位置


虽然我真诚地感谢您的意见,但我希望通过绑定以声明方式完成这个过程。 - Maxim Gershkovich
我努力寻找这样的示例,但不幸的是,大多数人似乎都在使用代码来实现这一点。也可以看看这个链接:http://www.codeproject.com/KB/WPF/SaveRestoreWPFWindowSize.aspx - Mamta D

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接