I'm trying to use a Pivot
control for a calendar type app, where each Pivot
view shows some infos about the current day. When the user swipes forward, the next day is shown. I implemented this by adding items to the end of the Pivot
Item collection, which works fine.
My problem occurs when the user tries to go backward to the previous day. In this case a new item is added at the beginning of the Pivot
item collection. Although the adding works, the shown Pivot item is always the wrong one (ie. the newly added item). Setting SelectedItem
on the Pivot
control doesn't help.
I think Pivot
might not be the right control for my task, so any help about what view to use or how fix my aforementioned problem with Pivot
are highly appreciated.
code for my Viewmodel that implements going forward/backward one day.
Pages
is bound to the Pivot ItemSource
.
public class TrackDayViewModel : HubViewModelBase
{
private DateTime _CurrentDay;
public DateTime CurrentDay
{
get { return _CurrentDay; }
set
{
if (value.CompareTo (_CurrentDay) != 0)
{
_CurrentDay = value;
OnPropertyChanged("CurrentDay");
}
}
}
public TrackDayViewModel ()
{
var day = DateTime.Now;
CurrentDay = day.Midnight();
Pages.Add(new DayViewModel(CurrentDay.AddDays(-1)));
Pages.Add(new DayViewModel(CurrentDay));
Pages.Add(new DayViewModel(CurrentDay.AddDays(1)));
SelectedItem = Pages[1];
this.PropertyChanged += (s, e) =>
{
if (e.PropertyName == "SelectedItem")
{
var si = SelectedItem as DayViewModel;
if (si != null)
{
var idx = Pages.IndexOf(SelectedItem);
if (idx==0)
{
Pages.Insert(0, new DayViewModel(si.Day.AddDays(-1)));
SelectedItem = Pages[1];
}
else if (idx == (Pages.Count - 1))
{
Pages.Add(new DayViewModel(si.Day.AddDays(1)));
}
}
}
};
}
}
EDIT: Change that solved my problem:
this.PropertyChanged += (s, e) =>
{
if (e.PropertyName == "SelectedItem")
{
var si = SelectedItem as DayViewModel;
if (si != null)
{
var idx = Pages.IndexOf(SelectedItem);
int nextIdx = (idx + 1) % 3;
int prevIdx = ((idx - 1)<0) ? 2 : (idx-1);
Pages[nextIdx] = new DayViewModel(si.Day.AddDays(1));
Pages[prevIdx] = new DayViewModel(si.Day.AddDays(-1));
}
}
};
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…