gpt4 book ai didi

mvvm - 在MVVM中加载LongListSelector

转载 作者:行者123 更新时间:2023-12-03 10:24:23 25 4
gpt4 key购买 nike

我是第一次使用MVVM Light,请多多包涵...

我的主页上有一个LongListSelector,并且正在使用RelayCommand在页面加载时将其与来自SQLCE数据库的数据一起加载。

在我的MainViewModel中,我有一个属性Workouts:

public const string WorkoutsPropertyName = "Workouts";

private PublicGrouping<DateTime, Workout> _workouts;
public PublicGrouping,DateDime, Workout> Workouts
{
get { return workouts; }
set
{
if (_workouts == value) { return; }
_workouts = value;
RaisePropertyChanged(WorkoutsPropertyName);
}
}

然后,在构造函数中,创建LoadedCommand:
public MainViewModel()
{
LoadedCommand = new RelayCommand(() =>
{
context = new XLogDataContext();

using (context)
{
if (context.Workouts.Count() > 0)
{
var workoutsByDate = from workout in context.Workouts
group workout by workout.WorkoutDate
into c
orderby c.Key
select c;
Workouts = workoutsByDate as PublicGrouping<DateTime, Workout>;
}
}
});
}

当RelayCommand运行时,“锻炼”始终返回null。我知道有返回的数据,所以我认为问题出在将LINQ查询转换为PublicGrouping。我也尝试过创建属性
ObservableCollection<PublicGrouping<DateTime, Workout>>

但这也不起作用。

更新:

我将RelayCommand更改为使用以下行:
Workouts = new PublicGrouping<DateTime, Workout>(workoutsByDate);

并为PublicGrouping添加了此构造函数:
private readonly IGrouping<TKey, TElement> _internalGrouping;

public PublicGrouping(IOrderedQueryable<IGrouping<DateTime, Workout>> workoutsByDate)
{
_internalGrouping = (IGrouping<TKey, TElement>) workoutsByDate;
}

我仍然在构造函数中的_internalGrouping分配上收到InvalidCastException。

最佳答案

这应该工作:

public const string WorkoutsPropertyName = "Workouts";

private List<PublicGrouping<DateTime, Workout>> _workouts;
public List<PublicGrouping<DateTime, Workout>> Workouts
{
get { return _workouts; }
set
{
if (_workouts == value)
{
return;
}



_workouts = value;

RaisePropertyChanged(WorkoutsPropertyName);
}
}

public MainViewModel()
{
LoadedCommand = new RelayCommand(() =>
{
context = new XLogDataContext();

using (context)
{
if (context.Workouts.Count() > 0)
{
var workoutsByDate = from workout in context.Workouts
group workout by workout.WorkoutDate
into c
orderby c.Key
select new PublicGrouping<DateTime, Workout>(c);
Workouts = workoutsByDate.ToList();
}
}
});
}

关于mvvm - 在MVVM中加载LongListSelector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6695254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com