【问题标题】:How to set Page Wide BindingContext in a XAML Page Header如何在 XAML 页面标题中设置 Page Wide BindingContext
【发布时间】:2018-10-26 15:13:04
【问题描述】:

在其标题中设置 XAML 页面的 bindingContext 的正确语法是什么(定义命名空间和 x:class 的位置)?

我知道可以设置

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

但是像下面这样的例子,看起来会更整洁

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

【问题讨论】:

    标签: xaml xamarin data-binding xamarin.forms


    【解决方案1】:

    以前有一个bug,第二种方法会导致两次创建ViewModel,不确定它是否还存在,你可以很容易地检查它。

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

    我会说你自己评估什么适合你的解决方案并坚持下去,这样它就会保持一致。

    P.S.:我并不是说你不应该在 XAML 中这样做,如果它在你的特定情况下有意义就这样做。

    【讨论】:

      猜你喜欢
      • 2016-12-08
      • 2018-09-21
      • 1970-01-01
      • 2016-12-26
      • 2010-10-04
      • 2016-11-27
      • 1970-01-01
      • 2020-03-10
      相关资源
      最近更新 更多