.NET MAUI无FindResource方法,如何获取资源中的MapViewModel?
解决.NET MAUI中替代WPF FindResource的问题
方法一:直接访问Resources字典
在.NET MAUI中,Element类自带Resources字典属性,这可以直接替代WPF里的FindResource方法,通过键名就能获取对应的资源。修改你的事件处理代码如下:
private void OnMapTapped(object sender, TappedEventArgs e) { // 从Resources字典中获取ViewModel var viewModel = this.Resources["MapViewModel"] as MapViewModel; if (viewModel == null) return; // 增加空值判断,避免空引用异常 Point? p = e.GetPosition(MainMapView); if (p == null) return; Point pT = p.Value; MapPoint mp = MainMapView.ScreenToLocation(pT); viewModel.createPoint(mp); }
方法二:更贴合MVVM模式的实现
既然你遵循MVVM模式,更规范的做法是把ViewModel设为页面的BindingContext,这样不需要手动从资源字典中取值:
- 修改XAML,将页面的BindingContext绑定到资源中的ViewModel:
<ContentPage ... BindingContext="{StaticResource MapViewModel}"> <ContentPage.Resources> <local:MapViewModel x:Key="MapViewModel"/> </ContentPage.Resources> <!-- 页面内容 --> </ContentPage>
- 事件处理中直接获取BindingContext:
private void OnMapTapped(object sender, TappedEventArgs e) { var viewModel = this.BindingContext as MapViewModel; if (viewModel == null) return; Point? p = e.GetPosition(MainMapView); if (p == null) return; Point pT = p.Value; MapPoint mp = MainMapView.ScreenToLocation(pT); viewModel.createPoint(mp); }
这种方式更符合MVVM的设计逻辑,代码也更简洁易维护。
内容的提问来源于stack exchange,提问作者user25472259
相关产品推荐
相关产品推荐

