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

时间:2016-06-29 08:21:27

标签: c# wpf mvvm data-binding

模型

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>

视图模型

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值添加到集合列表?

以上是我尝试过的代码。如果我喜欢上面的话,它会显示空引用异常。会出现什么问题?

更新

我在EmployeeDetails课程中有两个字段。因此,在添加到集合时,我必须为这两个字段提供输入。但是我只需要一个字段Name来插入集合。怎么做?

1 个答案:

答案 0 :(得分:1)

分析

_details字段似乎没有“初始化”。

解决方案

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

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