【发布时间】:2015-10-31 23:18:48
【问题描述】:
所以我有一个视图,我绑定到一个名为 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>
我的绑定类:
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
}
}
干杯。
【问题讨论】:
标签: c# data-binding binding xamarin