Skip to content

A small collection of general purpose MVVM helpers for any platform.

License

Notifications You must be signed in to change notification settings

industriousone/industrious-mvvm

Repository files navigation

MIT

Industrious.Mvvm

A small collection of general purpose MVVM helpers, for any platform or view framework, in a .NET Standard 2.0 package.

See Industrious.ToDo for usage examples in something resembling a real application.

Contents

Command

A general implementation of the ICommand interface, not tied to any particular view framework.

public class MyViewModel
{
    private String _value;

    public MyViewModel
    {
        ChangeValueCommand = new Command<String>(value =>
        {
            _value = value;
        });
    }

    public ICommand ChangeValueCommand { get; }
}

var viewModel = new MyViewModel();
viewModel.ChangeValueCommand.Execute("New value");

See Industrious.ToDo.ViewModels.ItemEditorViewModel.cs for a usage example.

NotifyPropertyChanged

Helper base class which makes working with INotifyPropertyChanged a little easier. Calling SetAndRaiseIfChanged() will update the provided field, and raise the PropertyChanging and PropertyChanged events, if the value has changed.

public class MyViewModel : NotifyPropertyChanged
{
    private Int32 _myValue;

    public Int32 MyValue
    {
        get => _myValue;
        set => SetAndRaiseIfChanged(ref _myValue, value);
    }
}

See Industrious.ToDo.ViewModels.ItemEditorViewModel.cs for a usage example.

TranslatingObservable

Given an ObservableCollection containing one type of data, translate it to a new ObservableCollection of a different data type. Useful for turning a collection of model objects into a collection of view-models, which can then be bound to a list or collection view.

public class Item
{}

public class ItemViewModel
{
    public ItemViewModel(Item item)
    {}
}

public class ItemListViewModel
{
    public class ItemListViewModel(ObservableCollection<Item> items)
    {
        Items = new TranslatingObservable<Item, ItemViewModel>(
            items,
            item => new ItemViewModel(item)
        );
    }

    public TranslatingObservable<Item, ItemViewModel> Items { get; }
}

The translated collection is "live": any changes published by the source ObservableCollection are mirrored by the translated collection, and the corresponding change events are raised.

If the target data type (ItemViewModel in this example) implements IDisposable, it's Dispose() method will be called automatically whenever an instance is removed from the translated list.

See Industrious.ToDo.ViewModels.ItemListViewModel.cs for a usage example.

Stay in touch

License

MIT

About

A small collection of general purpose MVVM helpers for any platform.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages