-
Notifications
You must be signed in to change notification settings - Fork 1
Event Bindings Examples
eiadxp edited this page Apr 24, 2019
·
4 revisions
In this examples we will introduce the XAML example followed by the equivalent code in C#. The code is written for WPF platforms but it should be the same for the remaining platforms. Please remember:
- UI elements names start with
$
or!
. - UI resources keys start with
#
or!
. - Keywords start with
@
or!
. - The symbol
!
will search for keyword, then UI element, then UI resource. - Multiple events definitions are separated by
,
.
- Simple default event binding to a method that has no parameters:
<Button tools.Events.Bindings="Cancel"/>
Or:
<Button tools.Events.Bindings="Cancel()"/>
Private void Button_Click(object sender, EventArgs e)
{
(Button.DataContext as ViewModel).Cancel();
}
- Binding an event to a method that takes single parameter and pass the
Text
property of the control to the method:
<TextBox tools.Events.Bindings="LostFocus=ValidateName(!this.Text)"/>
Or:
<TextBox tools.Events.Bindings="LostFocus=ValidateName(@this.Text)"/>
Private void TextBox_LostFocus(object sender, EventArgs e)
{
var textBox = sender as TextBox;
(textBox.DataContext as ViewModel).ValidateName(textBox.Text);
}
- Binding to method in a data context in another control:
<TextBox tools.Events.Bindings="LostFocus=$root.DataContext.ValidateName(!this.Text),GotFocus=!root.Clear(@sender)"/>
Starting by v1.2.0 you can delete DataContext part of the path and just write:
<TextBox tools.Events.Bindings="LostFocus=$root.ValidateName(!this.Text),GotFocus=!root.DataContext.Clear(@sender)"/>
Both syntax can be translated to the following C# code:
Private void TextBox_LostFocus(object sender, EventArgs e)
{
var textBox = sender as TextBox;
var root = textBox.GetName("root");
(root.DataContext as ViewModel).ValidateName(textBox.Text);
}
Private void TextBox_GotFocus(object sender, EventArgs e)
{
var textBox = sender as TextBox;
var root = textBox.GetName("root");
(root.DataContext as ViewModel).Clear(sender);
}
- Binding an event to a command and pass the
Text
property of the control to the `Execute' method:
<TextBox tools.Events.Bindings="LostFocus=ValidateNameCommand(!this.Text)"/>
Or:
<TextBox tools.Events.Bindings="LostFocus=ValidateNameCommand(@this.Text)"/>
Private void TextBox_LostFocus(object sender, EventArgs e)
{
var textBox = sender as TextBox;
var command = (textBox.DataContext as ViewModel).ValidateNameCommand as ICommand;
if (command.CanExecute(textBox.Text)) command.Execute(textBox.Text);
}