[英]MVVM-Light and WP7 ViewModel tombstoning isn't working
我已经尝试按照Joost Van Schaik在墓碑上的文章中的步骤进行操作,但是无法使它对我有用。 我无疑做错了什么。 在我的ViewModel中:
private string _foobar ="init";
public string testStr
{
get
{
return _foobar;
}
set
{
_foobar = value;
}
}
在我的页面中:
<TextBox x:Name="tBoxTest" Text="{Binding testStr, Mode=TwoWay}" />
当应用程序运行时,在tBoxTest中更改值可以很好地设置_foobar,但尝试对其进行序列化,就好像它忘记了该实例一样??? 任何帮助将不胜感激。
通过执行以下操作,我能够使墓碑工作,并使对象对我所有的ViewModel可见:
在模型类中,我添加了:
private static Model1 _instance;
public static Model1 Instance
{
get { return _instance; }
set { _instance = value; }
}
public static void CreateNew()
{
if (_instance == null)
{
_instance = new Model1();
_instance.FirstString = "init";
}
}
然后在ApplicationExtensions.cs中添加:
public static void SaveToIsolatedStorage(this Application app, Model1 model)
{
var dataFileName = GetIsFile((model.GetType()));
using (var userAppStore =
IsolatedStorageFile.GetUserStoreForApplication())
{
if (userAppStore.FileExists(dataFileName))
{
userAppStore.DeleteFile(dataFileName);
}
using (var iss = userAppStore.CreateFile(dataFileName))
{
SilverlightSerializer.Serialize(model, iss);
}
}
}
在App.xaml.cs中,我将LoadModel()更改为:
private void LoadModel()
{
try
{
Model1.Instance = this.RetrieveFromIsolatedStorage<Model1>();
}
catch (Exception) { }
if (Model1.Instance == null) Model1.CreateNew();
}
所有这些都在我的ViewModel文件中完成了以下工作:
public string TestStr
{
get
{
return Model1.Instance.FirstString;
}
set
{
Model1.Instance.FirstString = value;
}
}
就是说,我的意思是Model1对象正在被序列化并且tombstoning正在工作 -至少我得到了我想要的东西。 我通过在应用程序,手机设置之间导航,关闭和打开手机,锁定手机以及在其他手机中从应用程序中调用手机进行了很多测试。 反序列化时的性能很棒。 我可以和var一起工作。
话虽如此,Van Schaik先生回答了一个请求帮助: “如果您是从MVVMLight ViewModelBase进行子类化的,那么您应该像这样从设置器调用RaisePropertyChanged:
私有字符串_foobar =“ init”;
公共字符串TestStr {get {return _foobar; }
set
{
RaisePropertyChanged("TestStr");
_foobar = value;
}
}
RaisePropertyChanged通知任何侦听视图(即,绑定到它的TextBox)属性已更改,并且应当更新其内容。 这是一个至关重要的机制。”
因此,我将使用最初尝试的方法,但还要添加RaisePropertyChanged来查看其作用。
更新
尽管我在MainViewModel.cs文件中实现了RaisedPropertyChanged(使用代码片段mvvminpc),但对序列化ViewModel中创建的任何内容仍然没有效果(与其他功能一样好)。 我可能仍然在做错事,但这也可能是因为视图模型继承自受保护的类( Laurent Bugnion的回答 )。 我(非常不情愿地)尝试将此类从受保护的类更改为公共类,然后重新编译,但是这对我的情况没有帮助,并且我讨厌派生这样的引用库。 无论如何,我只是在App.xaml.cs中创建Model1实例而向前迈进。 似乎可以工作。 在讨论的同时,我修改了Van Schaik的方法之一以接受任何类型的对象:
public static void SaveToIsolatedStorage<T>(this Application app, T obj)
where T : class
{
var dataFileName = GetIsFile(typeof(T));
using (var userAppStore =
IsolatedStorageFile.GetUserStoreForApplication())
{
if (userAppStore.FileExists(dataFileName))
{
userAppStore.DeleteFile(dataFileName);
}
using (var iss = userAppStore.CreateFile(dataFileName))
{
SilverlightSerializer.Serialize(obj, iss);
}
}
}
根据您发布的代码,并没有即时的答案。
我的调试建议是:
如果您完全从该文章中复制了代码,则向空的catch处理程序中添加一些内容(消息框?)-`catch(Exception){}
使用调试器将断点放入LoadModel和SaveToIsolatedStorage方法中
使用这些断点逐步执行“加载并保存”代码-代码是否正确加载和保存?
老实说,遇到这样的问题,自己做一点调查比在这里问问题要好得多(IMO!)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.