我看不到我在哪里做错了。通常,我已经正确实现了一切以在我的 Xamarin.Forms AppShell 项目中使用按钮命令,但按钮不会触发。也许有人可以看到这个问题?
我不知道它是否相关,尽管按钮的页面/视图是一个孩子。我正在使用来自父视图的 TabBar 导航到它,如下所示:
AppShell.xaml:
xmlns:local="clr-namespace:LVNGtoGo.Views"
<TabBar>
<ShellContent Title="Home" Icon="home_icon.png" Route="AboutPage" ContentTemplate="{DataTemplate local:AboutPage}" />
<ShellContent Title="B O M" Icon="new_icon.png" Route="NewBomPage" ContentTemplate="{DataTemplate local:NewBomPage}" />
</TabBar>
带有 INotifyPropertyChanged 的 BaseViewModel:
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
var changed = PropertyChanged;
if (changed == null)
return;
changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
ViewModel 继承自 BaseViewModel 和 Command 的构造函数:
public class NewBomViewModel : BaseViewModel
{
private string text;
public ICommand RallyCarCommand { get; }
public NewBomViewModel()
{
RallyCarCommand = new Command(ChooseRallyCar);
}
private void ChooseRallyCar()
{
text = "Rally Car was chosen!!!";
}
public string Text
{
get => text;
set => SetProperty(ref text, value);
}
}
XAML 与绑定上下文:
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="LVNGtoGo.Views.NewBomPage"
xmlns:vm="clr-namespace:LVNGtoGo.ViewModels"
Shell.PresentationMode="ModalAnimated"
Title="Create new B O M">
<ContentPage.BindingContext >
<vm:NewBomViewModel />
</ContentPage.BindingContext>
<StackLayout Spacing="3" Padding="15" >
<Label Text="{Binding Text}" VerticalOptions="Center" Margin="20" />
<Button Text="Click me" Command="{Binding RallyCarCommand}" />
</StackLayout>
</ContentPage>