所以我有一个View,我已经绑定了一个名为Timers的Timer对象列表(我已经制作了自定义类),并且在视图中我添加了一个启动和删除按钮。当用户单击开始时,我希望他们能够调用与该按钮关联的相关计时器对象方法startTimer()。我怎么能这样做?
查看代码:
<ContentPage.Content>
<StackLayout Orientation="Vertical">
<ListView ItemsSource="{Binding Timers, Mode=TwoWay}" SeparatorVisibility="None">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout HorizontalOptions="StartAndExpand" Orientation="Horizontal">
<StackLayout Padding="10,0,0,0" VerticalOptions="StartAndExpand" Orientation="Vertical">
<Label Text="{Binding _name, Mode=TwoWay}" YAlign="Center"/>
<Label Text="{Binding _startTime, Mode=TwoWay}" YAlign="Center" FontSize="Small"/>
</StackLayout>
<Button Text="Start" //button to associate with method//></Button>
<Button Text="Remove"></Button>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Button Text="Add New" Clicked="AddNewTimer"/>
</StackLayout>
</ContentPage.Content>
我的Binded Class:
public class MainViewModel : INotifyPropertyChanged
{
public MainViewModel ()
{
Timers = DependencyService.Get<ISaveAndLoad> ().LoadTimers ();
if (Timers == null) {
Timers = new ObservableCollection<Timer> ();
}
}
//When property changes notifys everything using it.
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private ObservableCollection<Timer> _timers;
public ObservableCollection<Timer> Timers {
get { return _timers; }
set {
_timers = value;
NotifyPropertyChanged ("Timers");
}
}
private string _title;
public string Title{
get{
return _title;
}
set{
_title = value;
NotifyPropertyChanged ();
}
}
}
计时器类:
public class Timer
{
public int _startTime { get; set;}
public bool _hasStarted{ get; set; }
public string _name { get; set; }
public Timer (string name, int startTime, bool hasStarted = false)
{
_name = name;
_startTime = startTime;
_hasStarted = hasStarted;
}
public void startTimer(){
//do something here
}
}
干杯。
答案 0 :(得分:1)
在View XAML代码中,您应该将其添加到开始按钮:
<Button Text="Start" Command={Binding btnStartCommand} />
然后在你的&#34;我的Binded Class:&#34;你应该创建de ICommand属性并在构造函数上初始化它,然后创建命令,如下所示:
public ICommand btnStartCommand {get; set;}
public MainViewModel()
{
btnStartCommand = new Command(StartCommand);
}
public void StartCommand()
{
//here you create your call to the startTimer() method
}
希望这可以帮到你, 欢呼声。