0

我在MvxAppCompatActivity整个项目中一直在使用,但在这种特定情况下,我必须使用MvxAppCompatDialogFragment.

不幸的是,在这种情况下,我以某种方式丢失了 ViewModel 的绑定上下文。

移动测试视图

[MvxDialogFragmentPresentation]
[Register(nameof(MobileScreenTestView))]
public class MobileTestView : MvxAppCompatDialogFragment<MobileTestViewModel>
...
    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        return inflater.Inflate(Resource.Layout.mobile_screen, container, false);
    }
...

移动测试视图模型

public class MobileTestViewModel : MvxViewModel<MInput, MResult>
...
public string Instructions { get; set; } = "Instructions";
...

mobile_screen.axml

...
<TextView
    android:id="@+id/text_mobile"
    android:layout_width="match_parent"
    android:layout_height="44dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:gravity="center_vertical|center_horizontal"
    tools:text="Scan"
    local:MvxBind="Text Instructions" />
...

local:MvxBind="Text Instructions"不再工作了,但我已经检查过了,它在视图模型中设置为OnCreateView().

上面的代码适用于MvxAppCompatActivity.

如果我想做的事情是不可能的,我总是可以这样做

view.FindViewById<TextView>(Resource.Id.text_mobile).Text = ViewModel.Instructions;

并不是我真的需要使用local:MvxBind,但我想知道我做错了什么。

更新- 对于任何有同样问题的人:

将方法更改OnCreateView为:

public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    base.OnCreateView(inflater, container, savedInstanceState);

    return this.BindingInflate(Resource.Layout.mobile_screen, container, false);
}

并且您的 BindingContext 将正常工作。

4

1 回答 1

1

正如您自己注意到的那样,您必须使用this.BindingInflate而不是LayoutInflater使用OnCreateView. 这是因为我们没有办法截取 MvvmCross 中的 Fragment 生命周期来提供我们自己的 Layout Inflater。

BindingInflate 所做的是遍历视图层次结构并查找应用于视图的所有自定义属性,在您的情况下Text Instructions,并在 View 和 ViewModel 之间应用这些绑定。

因此,无论何时使用 Fragments,您都应该使用 BindingInflate。

于 2018-12-22T08:26:48.713 回答