1

我是 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 中存在两个文本框和一个按钮控件。

感谢您。

危险品

4

2 回答 2

0

首先更改您的xml。正如许多妖精所说:=您需要将文本框的 Text 属性绑定到 ViewModel 上的字符串属性,您 应该如下所示

<Grid x:Name="LayoutRoot">   <StackPanel    
                <TextBox Text="{Binding FirstName,Mode=TwoWay" />
        <TextBox Text="{Binding FirstName,Mode=TwoWay" />
                <Button Content="Add Record" Command="{Binding AddTestUserRecord}" />   </StackPanel> </Grid> 

在您看来,模型代码应该是这样的。

Private _FirstName As String    Public Property FirstName() As String
    Get
        Return _FirstName 
    End Get
    Set(ByVal value As String)
        _FirstName = value RaisePropertyChanged(FirstName)
    End Set
End Property



Private _LastName As String   Public Property LastName() As String
    Get
        Return _LastName 
    End Get
    Set(ByVal value As String)
        _LastName = value RaisePropertyChanged(LastName)
    End Set
End Property 


 Private _AddTestUserRecord As ICommand
Public Property AddTestUserRecord() As ICommand
    Get
        If _AddTestUserRecordIs Nothing Then
            _AddTestUserRecord= New RelayCommand(Nothing, AddressOf AddUser)
        End If
        Return _rad_Map_Loaded
    End Get
    Set(ByVal value As ICommand)
        _AddTestUserRecord= value
    End Set
End Property

Public Sub AddUser()
   Try

Using db As New DBDataContext()
    Dim test As New TestUser() With { _
        Key .FirstName = me.FirstName, _
        Key .LastName = me.LastName _
    }
    db.TestUser.InsertOnSubmit(test)
    db.SubmitChanges()
End Using Catch ex As Exception     Return False  End Try    End Sub

该代码格式不正确,并且在 vb 中也是如此,但它可以让您公平地了解您必须做什么。

于 2013-09-01T06:27:17.487 回答
0

您需要将文本框的 Text 属性绑定到 ViewModel 上的字符串属性,当调用 AddTestUserRecord 命令的“执行”方法时,只需获取属性并调用逻辑以将值插入数据库。

于 2011-09-16T20:22:21.497 回答