问题描述
我看不到我在哪里做错。通常,我已经正确实现了所有内容,以便在Xamarin.Forms AppShell项目中使用button命令,但是不会触发按钮。也许有人可以看到问题?
虽然按钮的页面/视图是孩子,但我不知道它是否相关。我从这样的父视图中使用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));
}
}
从Baseviewmodel和构造方法继承的viewmodel:
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>
解决方法
您要设置内部私有字段,而不是公共财产
text = "Rally Car was chosen!!!";
应该是
Text = "Rally Car was chosen!!!";