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 apartial record
.internal partial record MainModel { }
-
Add a new
partial record
above namedCountable
. 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
andStep
properties to theCountable
's primary constructor.internal partial record Countable(int Count, int Step) { }
-
Add an
Increment
method to theCountable
record. Thewith
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 theMainModel
class. The type must beIState<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 theMainModel
that will in turn call theCountable
'sIncrement
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());
}