我正在学习C#并希望创建一个简单的注册和登录表格来练习。我试图使用MVVM模式。因为将登录数据存储到文本文件中似乎更容易,然后从中读取以进行身份验证。但是StreamWriter出现了一个问题:System.Collections.ObjectModel.ObservableCollection`1 [LoginForm.Andmed.LoginData]
如果有人能说出问题或如何解决,我会非常感激。
视图模型:
class LoginVM
{
public string path = @"C:\Users\Dell\Desktop\data.txt";
private ObservableCollection<LoginData> andmed; // creating ObservableCollection of LoginData data.
public ObservableCollection<LoginData> Andmed
{
get { return andmed; }
set { andmed = value; }
}
public LoginVM()
{
this.andmed = new ObservableCollection<LoginData>();
}
public void lisaAndmed(string user, string pass)//adds data to ObservableCollection
{
this.andmed.Add(new LoginData(user, pass));
}
public void salvestaAndmed()//
{
StreamWriter SW = new StreamWriter(path, true); // using streamwriter to save data from the Collection to the path defined
SW.WriteLine(this.andmed);
SW.Close();
}
public string autendi() // method for later purpose for authentification in login form.
{
StreamReader SR = new StreamReader(path);
path = SR.ReadToEnd();
SR.Close();
return path;
}
属性:
namespace LoginForm.Andmed
{
public class LoginData
{
private string username;
private string password;
public string Username
{
get { return username; }
set { username = value; }
}
public string Password
{
get { return password; }
set { password = value; }
}
public LoginData(string _username, string _password)
{
this.password = _password;
this.username = _username;
}
}
}
模型视图类:
public partial class MainWindow : Window
{
LoginVM mudel;
public MainWindow()
{
InitializeComponent();
mudel = new LoginVM();
this.DataContext = mudel;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
if (user.Text.Length > 0 && pass1.Password == pass2.Password)
{
success.Text = "Successfuly registered!" + user.Text;
error.Text = "";
mudel.lisaAndmed(user.Text, pass1.Password); // calling the method to add data into obsercablecooll
mudel.salvestaAndmed(); // now trying to save the data from obsservablecall
}
else if (pass1.Password != pass2.Password)
{
error.Text = "Passwords arent the same";
}
else
{
error.Text = "Username incorrect!";
}
Logimine logimine = new Logimine();
logimine.ShowDialog();
}
}
答案 0 :(得分:1)
此:
SW.WriteLine(this.andmed);
写入ObservableCollection<T>.ToString()
方法调用的结果,默认情况下是类型名称,因为ObservableCollection<T>
不会覆盖Object.ToString()
。
您必须使用任何序列化程序来保存和加载ObservableCollection<LoginData>
内容。例如,它可以是XmlSerializer
:
var serializer = new XmlSerializer(typeof(ObservableCollection<LoginData>));
var collection = new ObservableCollection<LoginData>
{
new LoginData { Username = "admin", Password = "123" },
new LoginData { Username = "johndoe", Password = "456" }
};
var sb = new StringBuilder();
// serialize
using (var writer = new StringWriter(sb))
{
serializer.Serialize(writer, collection);
}
// deserialize
using (var reader = new StringReader(sb.ToString()))
{
var collectionClone = serializer.Deserialize(reader);
}