我是WP dev的新手。我只想创建一个简单的数据库并使用它。
我创建了一个数据库,其中TABLE是Member,3列是ID,FirstName,LastName。然后我使用SQL server compact toolbox生成datacontext。
最后,我尝试完全制作应用程序。但是当我输入FirstName和LastName时......它没有显示结果。请帮帮我
代码如下:
Namecontext.cs
namespace PhoneApp6
{
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using System.ComponentModel;
using System;
using System.IO;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Data.Linq.Mapping;
using Microsoft.Phone.Data.Linq;
public class DebugWriter : TextWriter
{
private const int DefaultBufferSize = 256;
private System.Text.StringBuilder _buffer;
public DebugWriter()
{
BufferSize = 256;
_buffer = new System.Text.StringBuilder(BufferSize);
}
public int BufferSize
{
get;
private set;
}
public override System.Text.Encoding Encoding
{
get { return System.Text.Encoding.UTF8; }
}
#region StreamWriter Overrides
public override void Write(char value)
{
_buffer.Append(value);
if (_buffer.Length >= BufferSize)
Flush();
}
public override void WriteLine(string value)
{
Flush();
using(var reader = new StringReader(value))
{
string line;
while( null != (line = reader.ReadLine()))
System.Diagnostics.Debug.WriteLine(line);
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
Flush();
}
public override void Flush()
{
if (_buffer.Length > 0)
{
System.Diagnostics.Debug.WriteLine(_buffer);
_buffer.Clear();
}
}
#endregion
}
public partial class NameContext : System.Data.Linq.DataContext
{
public bool CreateIfNotExists()
{
bool created = false;
if (!this.DatabaseExists())
{
string[] names = this.GetType().Assembly.GetManifestResourceNames();
string name = names.Where(n => n.EndsWith(FileName)).FirstOrDefault();
if (name != null)
{
using (Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name))
{
if (resourceStream != null)
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(FileName, FileMode.Create, myIsolatedStorage))
{
using (BinaryWriter writer = new BinaryWriter(fileStream))
{
long length = resourceStream.Length;
byte[] buffer = new byte[32];
int readCount = 0;
using (BinaryReader reader = new BinaryReader(resourceStream))
{
// read file in chunks in order to reduce memory consumption and increase performance
while (readCount < length)
{
int actual = reader.Read(buffer, 0, buffer.Length);
readCount += actual;
writer.Write(buffer, 0, actual);
}
}
}
}
}
created = true;
}
else
{
this.CreateDatabase();
created = true;
}
}
}
else
{
this.CreateDatabase();
created = true;
}
}
return created;
}
public bool LogDebug
{
set
{
if (value)
{
this.Log = new DebugWriter();
}
}
}
public static string ConnectionString = "Data Source=isostore:/Name.sdf";
public static string ConnectionStringReadOnly = "Data Source=appdata:/Name.sdf;File Mode=Read Only;";
public static string FileName = "Name.sdf";
public NameContext(string connectionString) : base(connectionString)
{
OnCreated();
}
#region Extensibility Method Definitions
partial void OnCreated();
partial void InsertMember(Member instance);
partial void UpdateMember(Member instance);
partial void DeleteMember(Member instance);
#endregion
public System.Data.Linq.Table<Member> Member
{
get
{
return this.GetTable<Member>();
}
}
}
[global::System.Data.Linq.Mapping.TableAttribute()]
public partial class Member : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _ID;
private string _FirstName;
private string _LastName;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnIDChanging(int value);
partial void OnIDChanged();
partial void OnFirstNameChanging(string value);
partial void OnFirstNameChanged();
partial void OnLastNameChanging(string value);
partial void OnLastNameChanged();
#endregion
public Member()
{
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ID", DbType="Int NOT NULL", IsPrimaryKey=true)]
public int ID
{
get
{
return this._ID;
}
set
{
if ((this._ID != value))
{
this.OnIDChanging(value);
this.SendPropertyChanging();
this._ID = value;
this.SendPropertyChanged("ID");
this.OnIDChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_FirstName", DbType="NVarChar(100) NOT NULL", CanBeNull=false)]
public string FirstName
{
get
{
return this._FirstName;
}
set
{
if ((this._FirstName != value))
{
this.OnFirstNameChanging(value);
this.SendPropertyChanging();
this._FirstName = value;
this.SendPropertyChanged("FirstName");
this.OnFirstNameChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_LastName", DbType="NVarChar(100) NOT NULL", CanBeNull=false)]
public string LastName
{
get
{
return this._LastName;
}
set
{
if ((this._LastName != value))
{
this.OnLastNameChanging(value);
this.SendPropertyChanging();
this._LastName = value;
this.SendPropertyChanged("LastName");
this.OnLastNameChanged();
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
我的添加列表页面:
namespace PhoneApp6
{
public partial class Showlist : PhoneApplicationPage
{
public Showlist()
{
InitializeComponent();
}
private void appBarOkButton_Click(object sender, EventArgs e)
{
if ((Addfirstname.Text.Length > 0) & (Addlastname.Text.Length >0))
{
Member add = new Member
{
FirstName = Addfirstname.Text,
LastName = Addlastname.Text,
};
// Add the name to the ViewModel.
App.ViewModel.AddName(add);
// Return to the main page.
if (NavigationService.CanGoBack)
{
NavigationService.GoBack();
}
}
}
private void appBarCancelButton_Click(object sender, EventArgs e)
{
// Return to the main page.
if (NavigationService.CanGoBack)
{
NavigationService.GoBack();
}
}
}
}
视图模型:
namespace PhoneApp6
{
public class NameViewModel : INotifyPropertyChanged
{
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
// Used to notify Silverlight that a property has changed.
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
// LINQ to SQL data context for the local database.
private NameContext nameDB;
// Class constructor, create the data context object.
public NameViewModel(string nameDBConnectionString)
{
nameDB = new NameContext(nameDBConnectionString);
}
//FirstName
private ObservableCollection<Member> _firstname;
public ObservableCollection<Member> FirstName
{
get { return _firstname; }
set
{
_firstname=value;
NotifyPropertyChanged("FirstName");
}
}
//LastName
private ObservableCollection<Member> _lastname;
public ObservableCollection<Member> LastName
{
get { return _lastname; }
set
{
_lastname = value;
NotifyPropertyChanged("LastName");
}
}
// Write changes in the data context to the database.
public void SaveChangesToDB()
{
nameDB.SubmitChanges();
}
// Query database and load the collections and list
public void LoadCollectionsFromDatabase()
{
// Specify the query for First in the database.
var firstnameInDB = from Member first in nameDB.Member
select first;
var lastnameInDB = from Member last in nameDB.Member
select last;
FirstName = new ObservableCollection<Member>(firstnameInDB);
LastName = new ObservableCollection<Member>(lastnameInDB);
}
//add
public void AddName(Member add)
{
// Remove the to-do item from the "all" observable collection.
FirstName.Add(add);
LastName.Add(add);
nameDB.SubmitChanges();
}
//delete
public void DeleteName(Member delete)
{
// Remove the to-do item from the "all" observable collection.
FirstName.Remove(delete);
LastName.Remove(delete);
nameDB.Member.DeleteOnSubmit(delete);
nameDB.SubmitChanges();
}
}
}
我在XAML中的展示列表:
<StackPanel Orientation="Vertical" Margin="0,0,0,366">
<TextBlock Text="FirstName" HorizontalAlignment="Center" FontSize="20" />
<TextBlock Text="{Binding FN}" FontSize="20" Foreground="Yellow" />
</StackPanel>
<StackPanel Orientation="Vertical" Margin="0,315,0,0">
<TextBlock Text="LastName" HorizontalAlignment="Center" FontSize="20" />
<TextBlock Text="{Binding LN}" FontSize="20" Foreground="Yellow" />
</StackPanel>
我在Cs中的展示列表:
namespace PhoneApp6
{
public partial class Page1: PhoneApplicationPage
{
public Page1()
{
InitializeComponent();
// Set the page DataContext property to the ViewModel.
this.DataContext = App.ViewModel;
}
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
// Save changes to the database.
App.ViewModel.SaveChangesToDB();
}
}
}