我正在做一个简单的xamarin表单应用程序,其中有一个TimeAttendance模型,一个列表视图页面和一个时间输入页面。当我从列表中选择一个时间条目时,它将带我进入添加/编辑页面,在此页面中,我可以更改所有下拉/输入/时间选择器值,并且可以正确保存。
我遇到的问题是我要根据开始时间和结束时间计算总时数。当我关闭一天时,此值将正确保存,但是即使设置了绑定属性,它也不会在UI中更新。我可以在后端代码中看到该值已更新,但除非关闭一天并再次打开它,否则它不会反映在UI中。
似乎从源到目标的绑定只是在第一次加载时触发,但是我一直在阅读,并且这些视图已被defualt设置为双向绑定。
xaml代码:
<Label Text="Total Hours"/>
<Label x:Name="totalHours"
Text="{Binding TotalHours}"/>
<Button Text="CLOSE" Clicked="CloseDay_Clicked"/>
<Button Text="DELETE" Clicked="Delete_Clicked"/>
后面的代码:
async void CloseDay_Clicked(object sender, EventArgs e)
{
var timeEntry = (TimeAttendance)BindingContext;
timeEntry.idUser = 1;
await App.Database.SaveTimeAttendanceAsync(timeEntry);
//await Navigation.PopAsync();
}
async void TimePicker_timeChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == TimePicker.TimeProperty.PropertyName)
{
var timeEntry = (TimeAttendance)BindingContext;
var totalHours = timeEntry.EndTime - timeEntry.StartTime;
timeEntry.TotalHours = totalHours.Hours + (totalHours.Minutes / 15) * 0.25;
}
}
bindingContext是从列表页面设置的:
async void OnListViewItemSelected(object sender, SelectedItemChangedEventArgs e)
{
await Navigation.PushAsync(new TimeAttendanceEntryPage
{
BindingContext = e.SelectedItem as TimeAttendance,
});
}
我的考勤模式:
public class TimeAttendance
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public int idUser { get; set; }
public DateTime Date { get; set; } = DateTime.Today;
public string Commodity { get; set; }
public string Exception { get; set; }
public string RequestType { get; set; }
public string RequestId { get; set; }
public TimeSpan StartTime { get; set; }
public TimeSpan EndTime { get; set; }
public string Activity { get; set; }
public double TotalHours { get; set; }
}
就像我说的那样,代码对于关闭和保存值的更新工作正常,我只是不知道为什么更新TotalHours时会正确保存它,但是我看不到直接绑定到该值的标签中的更改
答案 0 :(得分:1)
您只应该更改您的 Timeattendance 模型,让它实现 INotifyPropertyChanged 界面,如下所示:
public class TimeAttendance : INotifyPropertyChanged
{
...
double totalHours;
public double TotalHours {
set
{
if (totalHours != value)
{
totalHours = value;
OnPropertyChanged("TotalHours");
}
}
get
{
return totalHours;
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}