Xamarin 窗体按钮绑定
本文关键字:绑定 按钮 窗体 Xamarin | 更新日期: 2023-09-27 18:37:09
我正在尝试将按钮绑定到视图模型中的命令,但单击它时它不会触发:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
x:Class="MyNamespace.UI.Views.AuthenticationPage">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button Text="Authenticate" Command="{Binding AuthenticateCommand}" Grid.Row="0"/>
<Label Text="Locked" Grid.Row="0"/>
</Grid>
</ContentPage>
后端代码:
public partial class AuthenticationPage : ContentPage
{
public AuthenticationPage()
{
InitializeComponent();
this.BindingContext = new AuthenticationViewModel(this);
}
protected override bool OnBackButtonPressed()
{
return false;
}
}
我的视图模型:
public class AuthenticationViewModel
{
private ContentPage contentPage;
public ICommand AuthenticateCommand { get; set; }
public AuthenticationViewModel(ContentPage contentPage)
{
this.contentPage = contentPage;
AuthenticateCommand = new Command(test, () => true);
}
private void test()
{
}
}
我之前让它工作过,但在进行一些更改后它停止工作。我认为我不需要INotifyPropertyChanged
按钮命令,对吧?
我认为
这是因为您的标签与按钮在同一行并且它过时了,因此单击/触摸根本无法到达按钮。是的,你不需要通知命令的属性更改,只要你在构造函数中/在绑定发生之前初始化它。
尝试
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
x:Class="MyNamespace.UI.Views.AuthenticationPage">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Button Text="Authenticate" Command="{Binding AuthenticateCommand}" Grid.Row="0"/>
<Label Text="Locked" Grid.Row="1"/>
</Grid>
</ContentPage>