Uwp binding control getting Width in viewmodel

末鹿安然 提交于 2019-12-11 04:18:16

问题


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:

  1. x:Bind the SizeChanged event to a method in your view model.
  2. 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.
  3. Write a behavior which does basically the same thing as 2.


来源:https://stackoverflow.com/questions/41080880/uwp-binding-control-getting-width-in-viewmodel

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