
[英]How to provide Command-Property for custom control in MVVM (.NET MAUI)
[英]Bindable command in NET Maui for custom control is always null?
我正在尝试在基于地图的自定义控件中实现可绑定命令,以便提供单击地图控件中的图钉的操作,但 CustomMap 中的 OnSelectedPin 命令始终为 null? 我正在使用 MVVM 和 CommunityToolkit.Mvvm。
自定义地图.cs
public partial class CustomMap : Map
{
...
public static readonly BindableProperty OnSelectedPinProperty =
BindableProperty.Create(
nameof(OnSelectedPin),
typeof(RelayCommand),
typeof(CustomMap));
public RelayCommand OnSelectedPin
{
get { return (RelayCommand)GetValue(OnSelectedPinProperty); }
set { SetValue(OnSelectedPinProperty, value); }
}
...
private void Pin_Clicked(object sender, PinClickedEventArgs e)
{
// This method gets called when a pin in the map is clicked,
// but OnSelectedPin is always null
if (OnSelectedPin?.CanExecute(null) ?? false) //<-- HERE'S THE ISSUE
{
OnSelectedPin.Execute(null);
}
}
}
我的页面.xaml
...
<!-- Map -->
<controls:CustomMap
Grid.Row="1"
IsShowingUser="True"
MapType="{Binding MapType}"
CenterRegion="{Binding CurrentLocation}"
OnSelectedPin="{Binding OnSelectedPinCommand}"/>
...
我的页面.cs
public partial class MyPage : ContentPage
{
public MyPage(MyPageViewModel ViewModel)
{
BindingContext = ViewModel;
InitializeComponent();
}
}
MyPageViewModel.cs
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
...
public partial class MyPageViewModel : ObservableObject
{
...
[RelayCommand]
public void OnSelectedPin()
{
var ii = 1; // Just for debugging purposes
}
}
生成的命令的名称将根据方法名称创建。 生成器将在末尾使用方法名称和 append “Command”,如果存在,它将去除“On”前缀。 此外,对于异步方法,“Async”后缀也会在附加“Command”之前被删除。
因此,如果您使用“OnSelectedPin”作为 RelayCommand 名称,生成器将删除前缀“On”。
然后你使用OnSelectedPin="{Binding OnSelectedPinCommand}"
,会找不到 RelayCommand。
所以更改名称,不要使用“On”前缀。
希望它有效。
问题未解决?试试以下方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.