我是 MVVM 模式的新手(使用 Galasoft MVVM Light 工具包)。我创建了一个测试项目,我想通过 WCF 从数据库中获取一些记录。这工作正常,但我未能从 View 插入新记录;这是我的代码:
数据库
表名:TestUser(名字,姓氏)
WCF (NW客户)
两种方法
Public List<TestUser> GetAllUsers() [“LINQ2SQL Operation”]
Public bool AddUser(TestUser testuser)
Public bool AddUser(TestUser testuser)
{
try
{
using (DBDataContext db = new DBDataContext())
{
TestUser test = new TestUser()
{
FirstName = testuser.FirstName,
LastName = testuser.LastName
};
db.TestUser.InsertOnSubmit(test);
db.SubmitChanges();
}
}
catch (Exception ex)
{
return false;
}
return true;
}
银光项目
模型包括
ITestUserService.cs
测试用户服务.cs
public void AddTestTable(TestTableViewModel testuser, Action<bool> callback)
{
NWCustomerClient client = new NWCustomerClient("BasicHttpBinding_NWCustomer");
client.AddTestUserCompleted += (s, e) =>
{
var userCallback = e.UserState as Action<bool>;
if (userCallback == null)
{
return;
}
if (e.Error == null)
{
userCallback(e.Result);
return;
}
userCallback(false);
};
client.AddTestUserAsync(testuser.Model);
}
视图模型
测试用户视图模型
public TestUser User
{
get;
private set;
}
public const string DirtyVisibilityPropertyName = "DirtyVisibility";
private Visibility _dirty = Visibility.Collapsed;
public Visibility DirtyVisibility
{
get
{
return _dirty;
}
set
{
if (_dirty == value)
{
return;
}
_dirty = value;
RaisePropertyChanged(DirtyVisibilityPropertyName);
}
}
public TestUserViewModel (TestUser user)
{
User = user;
user.PropertyChanged += (s, e) =>
{
DirtyVisibility = Visibility.Visible;
};
}
主视图模型
public ObservableCollection<TestUserViewModel> TestTables
{
get;
private set;
}
public const string ErrorMessagePropertyName = "ErrorMessage";
private string _errorMessage = string.Empty;
public string ErrorMessage
{
get
{
return _errorMessage;
}
set
{
if (_errorMessage == value)
{
return;
}
_errorMessage = value;
RaisePropertyChanged(ErrorMessagePropertyName);
}
}
private ITestUserService _service;
public RelayCommand< TestUserViewModel> AddTestUserRecord
{
get;
private set;
}
public MainTestTableViewModel (ICustomerService service)
{
_service = service;
TestTables = new ObservableCollection<TestTableViewModel>();
service.GetAllTestTable(HandleResult);
}
private void HandleResult(IEnumerable<TestTable> result, Exception ex)
{
TestTables.Clear();
if (ex != null)
{
//Error
return;
}
if (result == null)
{
return;
}
foreach (var test in result)
{
var table = new TestTableViewModel(test);
TestTables.Add(table);
}
}
XAML
<Grid x:Name="LayoutRoot">
<StackPanel>
<TextBox Text="FirstName" />
<TextBox Text="LastName" />
<Button Content="Add Record" Command="{Binding AddTestUserRecord}" />
</StackPanel>
</Grid>
我想将记录添加到 TestTable(数据库表)中。如何插入记录?在 XAML 中存在两个文本框和一个按钮控件。
感谢您。
危险品