【发布时间】:2021-06-27 14:11:21
【问题描述】:
我已经被这个问题困扰了两天了。我想在使用数据绑定时一键禁用按钮。首先,我的 ViewModel 检查是否有可用的空闲停车位,然后如果有 0 个可用停车位,我的 Button 在调用构造函数后立即被禁用。如果有可用的停车位,一按后我想减少可用的停车位,这工作正常,但我的按钮仍然保持启用状态,所以我应该如何在按一下后将其禁用。 我的 ViewModel 类:
public class SpacesPageViewModel : INotifyPropertyChanged
{
public int CurrentSpaces;
public ICommand MyCommand { private set; get; }
// BANDAU NAUJA DALYKA
public ICommand myCommand
{
set
{
if(EmptySpaces == 0)
{
MyCommand.CanExecute(false);
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("myCommand"));
}
}
get
{
return MyCommand;
}
}
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<Location> AllSpaces { get; set; }
public ObservableCollection<Location> allSpaces { get { return AllSpaces; } }
public int EmptySpaces { get; set; }
public int emptySpaces
{
set
{
if(EmptySpaces != value)
{
EmptySpaces = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("emptySpaces"));
}
}
get
{
return EmptySpaces;
}
}
public SpacesPageViewModel(string street)
{
var result = LocationsDb.Locations
.Where(x => x.street == street)
.Select(g => g.emptySpaces)
.FirstOrDefault();
MyCommand = new Command(() =>
{
foreach (var item in LocationsDb.Locations.Where(x => x.emptySpaces == EmptySpaces))
{
if (item.emptySpaces > 0)
{
item.emptySpaces--;
emptySpaces = item.emptySpaces;
myCommand = MyCommand;
break;
}
}
}, () =>
{
if (EmptySpaces == 0)
return false;
else
return true;
});
EmptySpaces = result;
CurrentSpaces = result;
}
}
我的 XAML:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ParkingApp.Views.SpacesPage"
ControlTemplate="{StaticResource MyTemplate}"
>
<ContentPage.Content>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="1*"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Text="Reserve parking spot"
BackgroundColor="#e8e8e8" HorizontalTextAlignment="Center"
HeightRequest="50" VerticalTextAlignment="Center"
FontSize="30"/>
<Label Grid.Row="1" Text="{Binding emptySpaces}" FontSize="150" TextColor="Black" Margin="10"
HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand"/>
<Label Grid.Row="2" Text="Free Spaces Left" TextColor="Black" FontSize="35" VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand"/>
<Button Grid.Row="3" Margin="10" Text="RESERVE" Command="{Binding MyCommand}" FontSize="20"/>
</Grid>
</ContentPage.Content>
【问题讨论】:
-
这有点难,因为有很多奇怪的事情发生,可能会导致意想不到的行为。我将从关于绑定和
INotifyPropertyChanged的基本教程开始(您混淆了可绑定属性和支持字段)。 -
你可以使用按钮的
IsEnable属性。对其使用绑定并在单击按钮时为其处理布尔值。如果您在这方面也需要帮助,请告诉我 -
我不确定应该将属性 IsEnable 放在我的代码中的哪个位置。它应该是一个单独的函数来处理按钮吗?
-
@VidmantasTelksnys 你可以将
property IsEnable放入SpacesPageViewModel,然后也调用INotifyPropertyChanged,你可以检查SpacesPageViewModel的构造函数中是否有可用的空闲停车位,如果有,将IsEnable设置为true ,如果否,将IsEnable设置为假。如果点击按钮减少空闲车位,可以调用函数再次检查是否有空闲车位可用。
标签: c# xamarin button mvvm binding