Taoist
Taoist

Reputation: 341

Binding window location not working two way

I am trying to persist the location of a window, I have the following XAML (non-relevant parts removed)

<Window x:Class="App.MainWindow"
  Title="MainWindow" Name="mainWindow"
  Top="{Binding Source={StaticResource Settings}, Path=Default.PositionY}"
  Left="{Binding Source={StaticResource Settings}, Path=Default.PositionX}"
  AllowsTransparency="True" WindowStyle="None" SizeToContent="WidthAndHeight"
  Background="#01000000" Topmost="{Binding Source={StaticResource Settings}, Path=Default.AlwaysOnTop}"
   MouseLeftButtonDown="mainWindow_MouseLeftButtonDown" 

"Settings" is defined in App.xaml and maps to the app settings

A search on Google gives several examples of this using exactly the method I have used.

The binding of TopMost works exactly as expected, this value is persisted between runs The binding of Top and Left however only appears to work one way. The window picks up its location from the setting correctly but when moved, the settings are not updated. A breakpoint on my Settings.Save function shows that the Top and Left properties have changed as expected. Manually copying these values into the settings just before save works fine. I have tried explicitly specifying Mode=TwoWay to no effect (should be default anyway)

PositionX and PositionY are both user settings defined as type double

Moving the window is accomplished with the following mouse handler

private void mainWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs args)
{
  DragMove();
}

Any ideas why the two way binding only works one way?

Upvotes: 0

Views: 314

Answers (3)

Clemens
Clemens

Reputation: 128060

Well, it really doesn't work without explicitly setting TwoWay. I just tried this:

Top="{Binding Source={StaticResource Settings}, Path=Default.PositionY, Mode=TwoWay}" 
Left="{Binding Source={StaticResource Settings}, Path=Default.PositionX, Mode=TwoWay}" 

and that does the job.

Concerning INotifyPropertyChanged: that's not necessary because it's the other binding direction, i.e. the one that works once on startup. And it's possibly hard to implement in a generated class.

Upvotes: 2

Pieter Nijs
Pieter Nijs

Reputation: 445

What ColinE said: Make your you implement the INotofiyPropertyChanged interface correctly. It would help if you'd share the code of your Settings-class with us.

BUT also make sure that you specify your Binding Mode Mode=TwoWay, which is NOT the default as you suggest in your question.

Upvotes: 1

ColinE
ColinE

Reputation: 70122

In order for the bindings to update, the object that exposes the PositionY and PositionX properties needs to implement the INotifyPropertyChanged interface and raise the PropertyChanged event when these two properties change. You haven't shown this part of your code, but my guess is that you are not doing this.

Upvotes: 0

Related Questions