WPF window location binding

大兔子大兔子 提交于 2019-12-03 16:49:17

It's extremely simple to bind to user or application settings from a .settings file in WPF.

Here's an example of a window that gets its position and size from 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>

The settings look like this:

And to persist, I'm simply using the following code:

void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    Properties.Settings.Default.Save();
}

And here is an example for 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"> ...
Mamta D

The below links may help for storing application settings. There is no single property called Location in a WPF Window but you do have a LocationChanged event that you can handle and write your code accordingly.

A crude example would be:

private void Window_LocationChanged(object sender, EventArgs e)
        {
            var left = (double)GetValue(Window1.LeftProperty);
            var top = (double)GetValue(Window1.TopProperty);
             // persist these values
             . . .
        }

For persisting application settings:

c# - approach for saving user settings in a WPF application? settings-in-a-wpf-application

WPF Application Settings File

Where to store common application settings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!