问题
I'm currenly working on a UWP app using the map control. I'm doing this using mvvm (no framework). In my viewmodel I do a calculation on how many meters you actually see (width). I do this by calculating how many meters a pixel represent, and then I multiply this by the width of the control. And there is where the problem is. In WPF you had a mode OneWayToSource, which would set the source value and not change the target value. But this is missing in UWP. If I use a binding, I must set the width in my viewmodel. And this is something I don't want. I just want to get the width of the map. And that is not the only problem. I don't actually need the width ,because this gives NaN, what I need is the ActualWidth. But this is a backing field and you can't bind to this from xaml.
Is there a solution for this while still preserving the mvvm pattern?
回答1:
ActualWidth and ActualHeight should never be the source or target of a binding. They simply don't work in that situation. You'll need to obtain the size of the element by listening to its SizeChanged event. There are 3 ways you can do this:
- x:Bind the SizeChanged event to a method in your view model.
- Create an attached property which syncs its value to the size of the element by listening to SizeChanged events. You can then TwoWay bind to this property.
- Write a behavior which does basically the same thing as 2.
来源:https://stackoverflow.com/questions/41080880/uwp-binding-control-getting-width-in-viewmodel