如何使用MVVM将文本框值添加到列表中

本文关键字:添加 列表 何使用 MVVM 文本 | 更新日期: 2023-09-27 17:52:54

型号

public class EmployeeDetails
{
    public string Name { get; set; } 
    public int Age {get;set;}
} 
public class AddressDetails
{
    public EmployeeDetails EmployeeName { get; set; }
    public string City { get; set; }
} 

查看

<Window x:Class="ClassCollection.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:ClassCollection"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525"
    DataContext="{Binding Source={StaticResource loc},Path=ViewModel}"
    >
<Grid>
    <StackPanel Margin="0 20 0 0">
        <TextBox x:Name="txt1" Width="90" Height="20" Text="{Binding Details.EmployeeName}"/>
        <TextBox x:Name="txt2" Width="90" Height="20" Text="{Binding Details.City}"  Margin="0 20 0 0"/>
    </StackPanel>
    <Button x:Name="btn" Width="90" Height="25" Content="Add" Command="  {Binding AddCommand}"/>
</Grid>
</Window>

ViewModel

public class Viewmodel
{
    public ObservableCollection<AddressDetails> EmployeeList;
    public Viewmodel()
    {
        EmployeeList = new ObservableCollection<AddressDetails>();
        LoadCommand();
    }
    private AddressDetails _details;
    public AddressDetails Details
    {
        get { return _details; }
        set
        {
            _details = value;
        }
    }
    // Commands
    public ICommand AddCommand { get; set; }
    private void LoadCommand()
    {
        AddCommand = new CustomCommand(Add, CanAdd);
    }
    private bool CanAdd(object obj)
    {
        return true;
    }
    private void Add(object obj)
    {
        EmployeeList.Add(new AddressDetails { EmployeeName = Details.EmployeeName, City = Details.City });
    }
}

定位器

public class Locator
{
    private static Viewmodel viewmodel = new Viewmodel();
    public static Viewmodel ViewModel
    {
        get { return viewmodel; }
    }
}

如何使用MVVM将TextBox值添加到集合列表?

以上是我尝试过的代码。如果我喜欢上面的内容,它会显示null引用异常。会有什么问题?

更新

我在EmployeeDetails类中有两个字段。所以当添加到集合时,我必须为这两个字段提供输入。但是我只需要一个字段Name就可以插入到集合中。怎么做?

如何使用MVVM将文本框值添加到列表中

分析

_details字段似乎未"初始化"。

解决方案

请考虑引入适当的字段初始化,例如:

private readonly AddressDetails _details = new AddressDetails
    {
        EmployeeName = new EmployeeDetails()
    };