Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

xamarin - How to set Page Wide BindingContext in a XAML Page Header

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...