我正在使用Visual Studio使用MVVM light工具包为WP7创建笔记本应用程序。我想要设计时数据,但它没有显示。它在运行时工作,目前实现完全相同(DesignNoteDataService = NoteDataService)(我还没有真正的数据源)。
我做错了什么?
DesignNoteDataService(& NoteDataService)
public class DesignNoteDataService : INoteDataService
{
private List<Note> _noteList;
private void InitNotes()
{
_noteList = new List<Note>();
_noteList.Add(new Note(0, "Zahnarzt", "Zahnarzt morgen", Color.FromArgb(50, 20, 150, 50)));
_noteList.Add(new Note(0, "Party", "Sarah 7 Jahre", Color.FromArgb(50, 200, 10, 50)));
_noteList.Add(new Note(0, "Arbeit", "Projekt abgabe", Color.FromArgb(50, 20, 150, 50)));
_noteList.Add(new Note(0, "Meeting", "Abend Hotel @ Olten", Color.FromArgb(50, 20, 150, 50)));
}
void INoteDataService.GetNoteList(Action<List<Note>, Exception> callback)
{
if (_noteList == null)
InitNotes();
callback(_noteList, null);
}
void INoteDataService.GetNoteById(Action<Note, Exception> callback, int id)
{
if (_noteList == null)
{
InitNotes();
}
var item = (from n in _noteList
where n.Id.Equals(id)
select n).First();
callback(item, null);
}
}
MainViewModel
public class MainViewModel : ViewModelBase
{
private readonly INoteDataService _dataService;
/// <summary>
/// The <see cref="WelcomeTitle" /> property's name.
/// </summary>
public const string NoteListPropertyName = "NoteList";
private ObservableCollection<Note> _noteList;
/// <summary>
/// Gets the WelcomeTitle property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public ObservableCollection<Note> NoteList
{
get
{
return _noteList;
}
set
{
if (_noteList == value)
{
return;
}
_noteList = value;
RaisePropertyChanged(NoteListPropertyName);
}
}
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel(INoteDataService dataService)
{
_dataService = dataService;
NoteList = new ObservableCollection<Note>();
_dataService.GetNoteList(
(item, error) =>
{
if (error != null)
{
return;
}
foreach (var note in item)
{
NoteList.Add(note);
}
});
}
在MainPage.xaml中绑定
<ListBox ItemsSource="{Binding NoteList}"/>
ViewModelLocator的一部分
if (ViewModelBase.IsInDesignModeStatic)
{
SimpleIoc.Default.Register<INoteDataService, Design.DesignNoteDataService>();
}
else
{
SimpleIoc.Default.Register<INoteDataService, NoteDataService>();
}
答案 0 :(得分:2)
您很可能需要在视图中设置DataContext
。通常使用视图定位器执行此操作(有关示例,请参阅MVVM Light网站或here)。
或者,您可以在视图的构造函数中设置DataContext
,但是,您松散了“Blendability”。
哦,是的,您显然需要设置(注入)正确的数据服务。