使用MVVM WPF将数据保存到Collection和Display

时间:2016-02-05 07:30:33

标签: c# wpf mvvm

我有// This won't match because of the " after def var s2 = 'label1="abc" label2=\'def"\' label3="ghi"' // This won't match because there's an escaped single quote in the value var s2 = 'label1="abc" label2=\'def\\\'\' label3="ghi"' 类来实现Model。 我的视图有5个INotifyPropertyChanged,2个TextBox和一个Button来显示网格。 在我的ListView中,我之前在我的ViewModel课程的ObservableCollection中添加了默认值,并将其显示为Model

按钮实现使用ListViewICommand完成。

现在,我想要从用户RelayCommand向用户添加数据ObservableCollection。我怎样才能做到这一点? UI TextBox具有TextBox类属性的绑定。

我的Model

View

像这些有5个TextBoxes

<ListView Name="UserGrid" Grid.Row="1" Margin="4,178,12,13" ItemsSource="{Binding UserDatas}" > <TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,7,0,0" Name="txtUserId" VerticalAlignment="Top" Width="178" Text="{Binding UserId}" /> <TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,35,0,0" Name="txtFirstName" VerticalAlignment="Top" Width="178" Text="{Binding FirstName}" /> 类:

Model

ViewModel:

public class User : INotifyPropertyChanged
{
    private int userId;
    private string firstName;


public int UserId
    {
        get
        {
            return userId;
        }
        set
        {
            userId = value;
            RaisePropertyChanged("UserId");
        }
    }
}

}

public class UsersViewModel:INotifyPropertyChanged
{
    private ObservableCollection<User> userDatas;

    public ObservableCollection<User> UserDatas
    {
        get
        {
            if (userDatas == null)
            {
                userDatas = new ObservableCollection<User>();
            }
            return userDatas;
        }
        set
        {
            userDatas = value;
            RaisePropertyChanged("UserDatas");
        }
    }

现在我需要在LoadData方法中编写以从UI中的文本框中获取输入并将其存储在我的 private CommandBase _LoadCommand; public ICommand LoadCommand { get { if (this._LoadCommand == null) this._LoadCommand = new CommandBase(LoadData); return this._LoadCommand; } } private void LoadData(object obj) { //What need to be done here to access the textboxes of UI which are binded to User.cs class. User newUser = new User(); UserDatas.Add(newUser); }

1 个答案:

答案 0 :(得分:0)

你可以做几件事。最明显的是,有一个“添加新”命令,它创建一个新的空对象并将其存储在CurrentUserSelectedUser属性中。

此属性绑定到Template(或Form)的上下文。你有3个命令(添加新用户,保存用户,取消以取消添加新用户创建)。

例如

public class UsersViewModel : INotifyPropertyChanged
{
    public UsersViewModel() 
    {
        UserDatas = new ObservableCollection<User>();

        AddNewUserCommand = new RelayCommand(AddNewUser, param => !this.IsNewUser);
        SaveUserCommand = new RelayCommand(SaveUser);
        CancelNewUserCommand = new RelayCommand(CancelNewUser, param => this.IsNewUser);
    }

    private ObservableCollection<User> userDatas;
    public ObservableCollection<User> UserDatas
    {
        get { return userDatas; }
        set
        {
            userDatas = value;
            RaisePropertyChanged("UserDatas");
        }
    }

    private User selectedUser;
    public User SelectedUser 
    {
        get { return selectedUser; }
        set
        {
            selectedUser = value;
            RaisePropertyChanged("SelectedUser");
            RaisePropertyChanged("IsNewUser");
        }
    }

    public bool IsNewUser 
    {
        get 
        {
            if(SelectedUser==null)
                return false;

            return SelectedUser.UserId == 0;
        }
    }

    public ICommand AddNewUserCommand { get; private set; }
    public ICommand CancelNewUserCommand { get; private set; }
    public ICommand SaveUserCommand { get; private set; }

    private void AddNewUser() 
    {
        SelectedUser = new User();
    }

    private void SaveUser() 
    {
        // Just in case of concurency
        var newUser = SelectedUser;
        if(newUser == null) 
        {
            return;
        }

        var isNewUser = newUser.UserId == 0;

        // Persist it to the database
        this.userRepository.Add(newUser);
        this.userRepository.SaveChanges();

        // If all worked well, add it to the observable collection
        if(isNewUser) 
        {
            // Only add if new, otherwise it should be already in the collection
            UserDatas.Add(newUser)
        }
    }
}

但同样,我们非常气馁直接在模型上工作并将其绑定到View。您还应该为您的用户创建一个ViewModel并在其中放置验证(在IDataErrorInfo上实现UserViewModel接口)并处理状态,例如跟踪UserViewModel是否脏(即数据已更改)。

所有这些都是表示问题,而不是业务逻辑,因此它们属于ViewModel而不属于Model本身。