【发布时间】:2022-12-12 04:24:50
【问题描述】:
我正在尝试在 .NET MAUI 中构建自定义控件,它应该为其父级提供 ICommand 的 BindableProperty。这是我尝试实现的基本示例。
主页视图 (MainPage.xaml)
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:views="clr-namespace:SampleApp.Views"
x:Class="SampleApp.MainPage">
<views:MyCustomControl DoSomething="{Binding DoSomethingCommand}"></views:MyCustomControl>
</ContentPage>
MainPage 视图类 (MainPage.xaml.cs)
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
BindingContext = new MainPageViewModel();
}
}
主页视图模型 (MainPage ViewModel.cs)
public class MainPageViewModel : ObservableObject
{
public ICommand ProcessNewScoreCommand { get; }
public MainPageViewModel()
{
ProcessNewScoreCommand = new Command(DoSomething);
}
private void DoSomething()
{
// Do something
}
}
MyCustomControl 视图类 (MyCustomControl.xaml.cs)
public partial class MyCustomControl : ContentView
{
public static readonly BindableProperty DoSomethingProperty =
BindableProperty.Create(nameof(DoSomething), typeof(ICommand), typeof(MyCustomControl));
public ICommand DoSomething
{
get => (ICommand)GetValue(DoSomethingProperty);
set => SetValue(DoSomethingProperty, value);
}
public MyCustomControl()
{
InitializeComponent();
BindingContext = new MyCustomControlViewModel(DoSomething);
}
}
MyCustomControl 视图模型 (MyCustomControlViewModel.cs)
public class MyCustomControlViewModel : ObservableObject
{
public ICommand DoSomething { get; }
public MyCustomControlViewModel(ICommand doSomethingCommand)
{
DoSomething = doSomethingCommand;
}
private void PerformSomeLogic()
{
// Any calulations/logic
// ...
if (DoSomething.CanExecute(null))
{
// Execute command, so that parent component gets informed and can act.
DoSomething.Execute(null);
}
}
}
调试时,类MyCustomControl.xaml.cs 的属性DoSomething 始终为空。而且,它的设置器似乎在任何时候都不会被调用。我究竟做错了什么?
【问题讨论】: