29th March 2017 Olivier

Binding function with x:Bind

With the Windows 10 Anniversary update, there is a nice feature that has been added to the compiled binding (x: bind): there is a way bind to functions.
Like this:

Xaml:

Code

The function can also have parameters (parameters don’t need to be hardcoded, you can also pass another binding as parameter)

XAML

Code

There is no check on the type of the function parameters. It will be the first function with that name and the same number of parameters. The function must be accessible (public or internal)
There is also a way to make the two-way databinding.

XAML

C#

You can also bind an event to a function.

XAML

C#

The function does not neet have the signature of an event handler. A function without parameters will also do

XAML

C#

If you want to refresh the binding, there are 3 possibilities:

  1. If the function has at least a dependency property as a parameter: change the value of the property will refresh the binding
  2. If the function has at least a dependency property as a parameter: call OnPropertyChanged on the name of a parameter will refresh the binding
  3. Call OnPropertyChanged with String.Empty (which will refresh all the binding)

Example :

XAML

The property

Le code

If a function has no parameters and you want to refresh manualy, you can do it with method 3. You can do also with 1 and 2, if you add a bogus dependency parameter

Conclusion

Here, a nice feature, which is unfortunately not known enough.
The sample code is here

Mobile and Mixed Reality engineer , Arcana Studio
follow me

Leave a Reply

Your email address will not be published. Required fields are marked *