Skip to content

Instantly share code, notes, and snippets.

@cwensley
Last active October 24, 2017 20:52
Show Gist options
  • Save cwensley/a6375d4cdea5cf0f6864b4c32a0e7395 to your computer and use it in GitHub Desktop.
Save cwensley/a6375d4cdea5cf0f6864b4c32a0e7395 to your computer and use it in GitHub Desktop.
Shows how to hook up a button to a view model and update its background color based on logic in the view model.
using System;
using System.ComponentModel;
using System.Windows.Input;
using System.Runtime.CompilerServices;
using Eto.Forms;
using Eto.Drawing;
namespace Test
{
public class MyViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
static Color DefaultButtonBackgroundColor = new Button().BackgroundColor; // remember default button color
bool _buttonShouldBeRed;
Color _buttonBackgroundColor = DefaultButtonBackgroundColor;
public Color ButtonBackgroundColor
{
get { return _buttonBackgroundColor; }
set
{
_buttonBackgroundColor = value;
TriggerPropertyChanged();
}
}
Command _doSomethingCommand; // change Enabled property of this to automatically enable/disable button
public ICommand DoSomethingCommand => _doSomethingCommand ?? (_doSomethingCommand = new Command(DoSomething));
void DoSomething(object sender, EventArgs e)
{
_buttonShouldBeRed = !_buttonShouldBeRed;
ButtonBackgroundColor = _buttonShouldBeRed ? new Color(Colors.Red, 0.2f) : DefaultButtonBackgroundColor;
}
protected void TriggerPropertyChanged([CallerMemberName] string memberName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(memberName));
}
}
public class MyDialog : Form
{
public MyDialog()
{
var button = new Button { Text = "Click Me" };
button.BindDataContext(c => c.BackgroundColor, (MyViewModel m) => m.ButtonBackgroundColor);
button.BindDataContext(c => c.Command, (MyViewModel m) => m.DoSomethingCommand);
Content = new StackLayout
{
Spacing = 20,
Padding = 20,
Items = {
"Click the button below",
button
}
};
this.DataContext = new MyViewModel();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment