如何在XAML页面标题中设置页面范围的BindingContext [英] How to set Page Wide BindingContext in a XAML Page Header

查看:117
本文介绍了如何在XAML页面标题中设置页面范围的BindingContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在页眉(定义了名称空间和x:class的位置)中,设置XAML页的bindingContext的正确语法是什么?

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)?

我知道可以通过

<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

推荐答案

曾经有一个

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.

除此之外,没有适用于所有情况的灵丹妙药.如果您必须将一些数据传递给ViewModel构造函数怎么办?使用XAML会很棘手.很有可能有一个适当的IOC容器,将这些属性注入到ViewModel中,因此无论它如何在代码中而不是在XAML中发生.

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 .:我并不是说您不应该在XAML中执行此操作,如果在您的特定情况下有意义的话,请执行此操作.

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

这篇关于如何在XAML页面标题中设置页面范围的BindingContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆