2016-01-08 51 views
0

我必須在文本框中輸入一些數據,然後必須單擊保存按鈕,我寫的數據必須保存在下面的列表框中所有文本框。 我不能理解如何使用ICommand保存數據並將它傳遞給ListBox,這樣我就可以將它保存到Listbox中顯示的同一時刻。如何將數據保存到按鈕單擊事件列表框mvvm

一些這樣的事http://prntscr.com/9nm6u8

,但我無法理解如何將數據綁定,這樣當我把文本框,然後點擊保存必須更新該網格由數據全部使用MVVM只

我嘗試做的是(這obiously確實nothign這就是爲什麼我在這裏尋求幫助):

我完整的代碼:

型號:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace WpfApplication1 
{ 
    public class User : INotifyPropertyChanged 
    { 
     private int userId; 
     private string firstName; 
     private string lastName; 
     private string city; 
     private string state; 
     private string country; 

     public int UserId 
     { 
      get 
      { 
       return userId; 
      } 
      set 
      { 
       userId = value; 
       OnPropertyChanged("UserId"); 
      } 
     } 
     public string FirstName 
     { 
      get 
      { 
       return firstName; 
      } 
      set 
      { 
       firstName = value; 
       OnPropertyChanged("FirstName"); 
      } 
     } 
     public string LastName 
     { 
      get 
      { 
       return lastName; 
      } 
      set 
      { 
       lastName = value; 
       OnPropertyChanged("LastName"); 
      } 
     } 
     public string City 
     { 
      get 
      { 
       return city; 
      } 
      set 
      { 
       city = value; 
       OnPropertyChanged("City"); 
      } 
     } 
     public string State 
     { 
      get 
      { 
       return state; 
      } 
      set 
      { 
       state = value; 
       OnPropertyChanged("State"); 
      } 
     } 
     public string Country 
     { 
      get 
      { 
       return country; 
      } 
      set 
      { 
       country = value; 
       OnPropertyChanged("Country"); 
      } 
     } 
     #region INotifyPropertyChanged Members 
     public event PropertyChangedEventHandler PropertyChanged; 
     private void OnPropertyChanged(string propertyName) 
     { 
      if (PropertyChanged != null) 
      { 
       PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
      } 
     } 
     #endregion 
    } 
} 

視圖模型:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Input; 

namespace WpfApplication1 
{ 
    class UserViewModel 
    { 
     private IList<User> _UsersList; 
     public UserViewModel() 
     { 
      _UsersList = new List<User> 
      { 
       // new User{UserId = 1,FirstName="sam",LastName="Disouza",City="lonero",State="Depra",Country="USA"}, 
      }; 
     } 
     /* 
     * 
      public UserViewModel(User usr) 
     { 
      _UsersList = new List<User> 
      { 
       new User{UserId = usr.UserId,FirstName=usr.FirstName,LastName=usr.LastName,City=usr.City,State=usr.State,Country=usr.Country}, 
      }; 
     } 
     */ 
     public IList<User> Users 
     { 
      get { return _UsersList; } 
      set { _UsersList = value; } 
     } 
     private ICommand mUpdater; 
     public ICommand SaveCommand 
     { 
      get 
      { 
       if (mUpdater == null) 
        mUpdater = new Updater(); 
       return mUpdater; 
      } 
      set 
      { 
       mUpdater = value; 
      } 
     } 
     private class Updater : ICommand 
     { 
      #region ICommand Members 
      public bool CanExecute(object parameter) 
      { 
       return true; 
      } 
      public event EventHandler CanExecuteChanged; 
      public void Execute(object parameter) 
      { 
      } 
      #endregion 
     } 
    } 
} 

查看:

<Window x:Class="WpfApplication1.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid Margin="0,0,0,20"> 
     <Grid.RowDefinitions> 
      <RowDefinition Height="Auto"/> 
      <RowDefinition Height="*"/> 
      <RowDefinition Height="Auto"/> 
     </Grid.RowDefinitions> 
     <ListView Name="UserGrid" Grid.Row="1" Margin="4,178,12,13" ItemsSource="{Binding Users}" > 
      <ListView.View> 
       <GridView x:Name="grdTest"> 
        <GridViewColumn Header="UserId" DisplayMemberBinding="{Binding UserId}" Width="50"/> 
        <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="80" /> 
        <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" Width="100" /> 
        <GridViewColumn Header="City" DisplayMemberBinding="{Binding City}" Width="80" /> 
        <GridViewColumn Header="State" DisplayMemberBinding="{Binding State}" Width="80" /> 
        <GridViewColumn Header="Country" DisplayMemberBinding="{Binding Country}" Width="100" /> 
       </GridView> 
      </ListView.View> 
     </ListView> 
     <TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,7,0,0" Name="txtUserId" VerticalAlignment="Top" Width="178" Text="{Binding ElementName=UserGrid,Path=SelectedItem.UserId}" /> 
     <TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,35,0,0" Name="txtFirstName" VerticalAlignment="Top" Width="178" Text="{Binding ElementName=UserGrid,Path=SelectedItem.FirstName}" /> 
     <TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,62,0,0" Name="txtLastName" VerticalAlignment="Top" Width="178" Text="{Binding ElementName=UserGrid,Path=SelectedItem.LastName}" /> 
     <Label Content="UserId" Grid.Row="1" HorizontalAlignment="Left" Margin="12,12,0,0" Name="label1" VerticalAlignment="Top" /> 
     <Label Content="Last Name" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,60,0,0" Name="label2" VerticalAlignment="Top" /> 
     <Label Content="First Name" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,35,0,0" Name="label3" VerticalAlignment="Top" /> 
     <Button Content="Save" Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="310,50,0,0" Name="btnSave" 
       VerticalAlignment="Top" Width="141" 
       Command="{Binding Path=SaveCommad}" /> 
     <TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,143,0,0" x:Name="txtCity" VerticalAlignment="Top" Width="178" Text="{Binding SelectedItem.City, ElementName=UserGrid}" /> 
     <Label Content="Country" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,141,0,0" x:Name="label2_Copy" VerticalAlignment="Top" /> 
     <TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,88,0,0" x:Name="txtCountry" VerticalAlignment="Top" Width="178" Text="{Binding SelectedItem.Country, ElementName=UserGrid}" /> 
     <Label Content="City" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,86,0,0" x:Name="label2_Copy1" VerticalAlignment="Top" /> 
     <TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,115,0,0" x:Name="txtSTate" VerticalAlignment="Top" Width="178" Text="{Binding SelectedItem.State, ElementName=UserGrid}" /> 
     <Label Content="State" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,113,0,0" x:Name="label2_Copy2" VerticalAlignment="Top" /> 
    </Grid> 
</Window> 

View.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Data; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Imaging; 
using System.Windows.Navigation; 
using System.Windows.Shapes; 

namespace WpfApplication1 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
      this.DataContext = new UserViewModel(); 
     } 
    } 
} 

可能有人請幫助我在實現我的目標?

+0

你'UserViewModel'類需要實現'INotifyPropertyChanged'爲好。我在一個通用的'ViewModelBase'類中實現了所有viewmodel類繼承的類。 '用戶'應該是'ObservableCollection '。有一個從不爲空的User EditUser屬性 - 將文本框綁定到它的屬性。在保存命令中,列表視圖會將EditUser添加到用戶並創建一個新的空EditUser。要編輯現有用戶,最終用戶在列表視圖上雙擊並將雙擊項目分配給EditUser。 –

回答

1

我建議使用RelayCommand來綁定你的命令。另外,如果要將數據發送到命令,則需要添加命令參數。

看到這個代碼片段http://snipplr.com/view/13642/導入類和實現低於

2)有沒有在您的命令結合SaveCommad一個錯字應SaveCommand

添加CommandParameter {結合}這將發送您的視圖模型爲背景在您的視圖按鈕:

<Button Content="Save" Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="310,50,0,0" Name="btnSave" 
      VerticalAlignment="Top" Width="141" 
      Command="{Binding Path=SaveCommad}",CommandParameter{Binding} /> 

視圖模型:

RelayCommand _saveCommand;  
public ICommand SaveCommand  
{  
    get  
    {  
     if (_saveCommand== null)  
     {  
     _saveCommand= new RelayCommand(p => this.SaveCommand((object)p),  
     p => this.CanSaveCommand(p)); // you can set it to true for testing purpose or bind it to a property IsValid if u want to disable the button 
     }  
    return _saveCommand;  
    } 

} 

private void SaveCommand(object vm) 
{ 
    //Actual implementation to insert into list. 
} 
private bool CanSaveCommand(object vm) 
{ 
    return true; 
} 

YourViewModel : INotifyPropertyChange // to enable notification to your view 
private User _currentUser; 
public User CurrentUser {get return _currentUser;} set{_currentUser = value; NotifyPropertyChange("CurrentUser") 

//Or Simply Insert all property of user to your viewmodel so your input have acces to content 
private string _name; 
public string Name {get return _name;} set{_name = value; NotifyPropertyChange("Name") 

在你的XAML選項1:

Text={Binding CurrentUser.Name,Mode="TwoWay",UpdateSourceTrigger=PropertyChanged} 

在你的XAML選項2:

Text={Binding Name,Mode="TwoWay",UpdateSourceTrigger=PropertyChanged} 
+0

謝謝,我輸入要保存的文本的文本框的綁定呢,我做的綁定是正確的嗎? () – struggling

+0

爲什麼你保持commandParameter爲空(CommandParameter {Binding})? – struggling

+0

對於命令參數{binding}是實際窗口的datacontext(所以它是你的viewmodel) 對於文本框,你必須添加一個屬性到你的視圖模型 public User CurrentUser {get return _user;} set {_user =值; NotifyPropertyChanged(CurrentUser)} 在您的XAML 文本=「{結合CurrentUser.Name}」 或者簡單地增加用戶類 公共字符串名稱{_name回報你的視圖模型中的所有財產;}集合{_name =值; NotifyPropertyChange( 「名稱」); 並在您的xaml文本= {綁定名稱,模式=「TwoWay」UpdateOnSourceUpdate =「PropertyChange」//不知道它的正確屬性 – Guillaume

相關問題