0

What is the correct syntax for setting the bindingContext of a XAML page, in it's header (Where the namespaces and x:class is defined)?

I know it can be set by

<ContentView.ContextBinding>
<vm:RedViewModel/>
</ContentView.ContextBinding>

but something like the following For Example, would look neater

<?xml version="1.0" encoding="UTF-8" ?>
<ContentView x:Class="MVVMFramework.VVMs.Red.RedView"
             xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:vm="clr-namespace:MVVMFramework.VVMs.Red"
             BackgroundColor="Red"
             BindingContext="{Binding Source = {vm:RedViewModel}}"> //Something like this
Jungle_Jon
  • 57
  • 1
  • 7

1 Answers1

1

There used to be a bug with the second approach that lead to create the ViewModel twice, not sure if it is there anymore, you could easily check it.

Beside that, there is no silver bullet solution that will work for all cases. What if you have to pass some data to ViewModel constructor? That will be tricky with XAML. Most probably it will make sense to have an IOC container in place, to inject those properties to the ViewModel, so any how it will happen in code and not in XAML.

I would say evaluate yourself what is suitable for your solution and stick to it, so it will be consistent.

P.S.: I am not saying that you should not do it in XAML, do it if it make sense in you specific case.

EvZ
  • 11,889
  • 4
  • 38
  • 76