I can`t pass data from View input field to ViewModel. WPF, Prism

I'm trying to add a new user to the database using the following command:

 <Button IsDefault="True" Content="Зберегти" Command="{Binding AddUserCommand}">

However, it seems that the ViewModel class isn't being invoked. I'm not sure what I'm doing wrong. The namespace appears to be correct, and there are no binding errors shown in IntelliSense. I've tried debugging, but it seems the program doesn't even attempt to enter the constructor of the ViewModel class.

Here's my XAML view:

<Window x:Class="EmployeeDirectoryWPF.View.AddWindow" ...
        xmlns:vm="clr-namespace:EmployeeDirectoryWPF.ViewModel" 
        mc:Ignorable="d"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        d:DataContext="{d:DesignInstance Type=vm:AddViewModel}"
        WindowStyle="ToolWindow"
        ResizeMode="CanResizeWithGrip"
        WindowStartupLocation="CenterOwner"
        SizeToContent="WidthAndHeight"> 
       
        <TextBlock Grid.Row="1" Grid.Column="0" Text="Ім'я:" />
        <TextBox Grid.Row="1" Grid.Column="1" 
                 Text="{Binding  Name, Mode=TwoWay}" />    

        <StackPanel Grid.Row="10" Grid.Column="1" 
                    HorizontalAlignment="Center" 
                    Orientation="Horizontal" Margin="0,20">
            <Button IsDefault="True" Content="Зберегти"
                    Command="{Binding AddUserCommand}" Margin="0,0,25,0" />
        </StackPanel>
    </Grid>
</Window>

And here's my ViewModel class:

namespace EmployeeDirectoryWPF.ViewModel;

public class AddViewModel : BindableBase
{    
    private Employee _newEmployee;
    private ObservableCollection<Employee> _employees;    

    public Employee NewEmployee
    {
        get => _newEmployee;
        set => SetProperty(ref _newEmployee, value);
    }

    private bool _isEnabled;
    public bool IsEnabled
    {
        get { return _isEnabled; }
        set { SetProperty(ref _isEnabled, value); }
    }

    public DelegateCommand AddUserCommand { get; private set; }

    public AddViewModel(ObservableCollection<Employee> employees, MyDbContext db)
    {
        _employees = employees;
        _newEmployee = new Employee();
        _db = db;

        AddUserCommand = new DelegateCommand(AddNewEmployee)
            .ObservesCanExecute(() => IsEnabled);
    }

    private void AddNewEmployee()
    {
        try
        {
            if (!CanAddNewEmployee())
            {
                return;
            }

            _employees.Add(new Employee
            {
                Name = _newEmployee.Name,
                DateOfBirth = _newEmployee.DateOfBirth,                
            });

            _db.SaveChanges();

            NewEmployee = new Employee();
        }       
    } 

I'd appreciate any insights or suggestions. Thanks in advance!

Upvotes: 0

Views: 50

Answers (0)

Related Questions