0

I am trying t create a view that allows the user to insert a record into the DB. The project is structured according to the MVVM architecture.

In my view I am binding my UI elements like so:

<StackPanel Orientation="Horizontal">
      <Label Width="200">Equipment Number</Label>
      <TextBox Width='150'
               Text="{Binding Equipment.EquipmentSerialnumber, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />
    </StackPanel>

The view is bound to a view model, which holds the current property being modified:

public Equipment Equipment
{
    get { return _equipment; }
    private set
    {
    _equipment = value;
    OnPropertyChanged();
    }
}

In my view I have a button that is bound to command, which creates a new delegate command. So in the constructor for my view model, I set the method to execute when the button is pressed:

CreateEquipmentCommand = new DelegateCommand(OnCreateEquipmentExecute, OnEquipmentCreateCanExecute);

I am using Prism.Core to achieve this. When the user clicks the button, this method is called:

private async void OnCreateEquipmentExecute()
{
    var equipment = CreateNewEquipment();
    await _equipmentRepository.SaveAsync(); 
}

Which then calls the CreateNewEquipment method, that adds the equipment to the repo after creating it.

var equipment = new Equipment();
_equipmentRepository.Add(equipment);
return equipment;

My repo is stateful and maintains a connection to the db. This is the add method:

public void Add(Equipment equipment)
{
    _context.Equipments.Add(equipment);
}

SaveAsync() should save all the changes made to the db context, thereby creating an insert statement.

But when I click the button, my values from the view are not present in the equipment i am trying to insert. I'm unsure why that is. It gives me a validation error with the missing values.

1 Answer 1

1

You create new Equipment, but you don't map values from your bound view model. So in your CreateNewEquipment method you should do:

var equipment = new Equipment(){EquipmentSerialnumber = _equipment.EquipmentSerialnumber};
_equipmentRepository.Add(equipment);
return equipment;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I figured out why it wasn't working. I managed to solve it by calling the CreateNewEquipment method and setting its return value to my class property in the constructor of my view model, so my changes are now tracked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.