2015-08-08 85 views
0

所以我有一个视图,我已经绑定到计时器对象列表称为定时器(我做了自定义类),并在视图中我添加了一个开始和删除按钮。当用户点击开始时,我希望他们能够调用与按钮相关的相关定时器对象方法startTimer()。我怎样才能做到这一点?从按钮单击xamarin调用绑定类的方法。

查看代码:

<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> 

我绑定类:

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 
    } 
} 

干杯。

回答

1

在您查看XAML代码,您应该添加到您的启动按钮:

<Button Text="Start" Command={Binding btnStartCommand} /> 

然后在“我的绑定类:”你应该创建德ICommand的属性,并初始化它的构造函数,然后创建命令,像这样:

public ICommand btnStartCommand {get; set;} 
public MainViewModel() 
{ 
    btnStartCommand = new Command(StartCommand); 
} 
public void StartCommand() 
{ 
    //here you create your call to the startTimer() method 
} 

希望这可以帮助你, 干杯。