Skip to content

Instantly share code, notes, and snippets.

@kentcb
Created October 19, 2015 02:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kentcb/7e3bf0aea9ae7c20daee to your computer and use it in GitHub Desktop.
Save kentcb/7e3bf0aea9ae7c20daee to your computer and use it in GitHub Desktop.
ReactiveUI Example
public class MyViewModel : ReactiveObject
{
private readonly ReactiveCommand<object> saveCommand;
private readonly ObservableAsPropertyHelper<string> fullName;
private readonly ObservableAsPropertyHelper<string> initials;
private string firstName;
private string lastName;
private bool showLastNameFirst;
public MyViewModel()
{
var canSave = this
.WhenAnyValue(
x => x.FirstName,
x => x.LastName,
(first, last) => !string.IsNullOrEmpty(first) && !string.IsNullOrEmpty(last));
this.saveCommand = ReactiveCommand.Create(canSave);
this.saveCommand.Subscribe(_ => { /* save data */ });
this.fullName = this
.WhenAnyValue(
x => x.FirstName,
x => x.LastName,
x => x.ShowLastNameFirst,
(first, last, showLastFirst) => showLastFirst ? string.Format("{0} {1}", last, first) : string.Format("{0} {1}", first, last))
.ToProperty(this, x => x.FullName);
this.initials = this
.WhenAnyValue(
x => x.FirstName,
x => x.LastName,
(first, last) => (string.IsNullOrEmpty(first) ? "" : first.Substring(0, 1) + (string.IsNullOrEmpty(last) ? "" : last.Substring(0, 1))))
.ToProperty(this, x => x.Initials);
}
public ReactiveCommand<object> SaveCommand => this.saveCommand;
public string FullName => this.fullName.Value;
public string Initials => this.initials.Value;
public string FirstName
{
get { return this.firstName; }
set { this.RaiseAndSetIfChanged(ref this.firstName, value); }
}
public string LastName
{
get { return this.lastName; }
set { this.RaiseAndSetIfChanged(ref this.lastName, value); }
}
public bool ShowLastNameFirst
{
get { return this.showLastNameFirst; }
set { this.RaiseAndSetIfChanged(ref this.showLastNameFirst, value); }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment