Skip to content

Latest commit

 

History

History
74 lines (55 loc) · 2.61 KB

include-mvux.md

File metadata and controls

74 lines (55 loc) · 2.61 KB

ViewModel

So far, all the elements we've added to the MainPage have had their content set directly. This is fine for static content, but for dynamic content, we need to use data binding. Data binding allows us to connect the UI to the application logic, so that when the application logic changes, the UI is automatically updated.

As part of creating the application, we selected MVUX as the presentation framework. This added a reference to MVUX which is responsible for dealing with our Models and generating the ViewModels.

  • Add a new class named MainModel.

  • Update the MainModel class to be a partial record.

    internal partial record MainModel
    {
    }
  • Add a new partial record above named Countable. This record will be responsible for updating our counter's properties all while ensuring immutability. Learn more about immutable records here.

    internal partial record Countable
    {
    }
  • Add the Count and Step properties to the Countable's primary constructor.

    internal partial record Countable(int Count, int Step)
    {
    }
  • Add an Increment method to the Countable record. The with operator allows us to create a new instance of the object.

    public Countable Increment() => this with
    {
        Count = Count + Step
    };
  • Add the newly created Countable as a property in the MainModel class. The type must be IState<Countable> and we use => State.Value(...) to initialize it.

    public IState<Countable> Countable => State.Value(this, () => new Countable(0, 1));
  • Add a method named IncrementCounter to the MainModel that will in turn call the Countable's Increment method and therefore update the counter. You can find more information on commands in MVUX here.

    public ValueTask IncrementCounter()
        => Countable.UpdateAsync(c => c?.Increment());

The final code for the MainModel class should look like this:

namespace Counter;

internal partial record Countable(int Count, int Step)
{
    public Countable Increment() => this with
    {
        Count = Count + Step
    };
}

internal partial record MainModel
{
    public IState<Countable> Countable => State.Value(this, () => new Countable(0, 1));

    public ValueTask IncrementCounter()
        => Countable.UpdateAsync(c => c?.Increment());
}