首页 > 解决方案 > Xamarin Forms`ContentView`绑定不起作用

问题描述

我正在尝试从PageViewModel这里绑定一个属性是代码

使用 MVVM 交叉插件进行绑定。

页面视图模型

public class ScanPageViewModel : BasePageViewModel
    {
        private bool m_testing;


        public bool Testing
        {
            get => m_testing;
            set => Set(ref m_testing, value);
        }
    }

内容视图 Xamal

<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:dxui="http://dips.xamarin.ui.com"
             xmlns:Resources="clr-namespace:Visit.Mobile.Common.Resources;assembly=Visit.Mobile.Common"
             xmlns:Shared="clr-namespace:Visit.Mobile.Views.Shared;assembly=Visit.Mobile"
             xmlns:Scan="clr-namespace:Visit.Mobile.Views.Scan;assembly=Visit.Mobile"
             xmlns:Appearance="clr-namespace:Visit.Mobile.Appearance;assembly=Visit.Mobile"
             xmlns:PageViewModels="clr-namespace:Visit.Mobile.Common.ViewModels.PageViewModels;assembly=Visit.Mobile.Common"
             mc:Ignorable="d"
             x:Class="Visit.Mobile.Views.Scan.ScanPage"
             x:Name="contentView">

<ContentView.BindingContext>
        <PageViewModels:ScanPageViewModel/>
    </ContentView.BindingContext>

    <Grid RowSpacing="0"
          ColumnSpacing="0">

        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="285" />
            <RowDefinition Height="80" />
        </Grid.RowDefinitions>

<Label IsVisible="{Binding Testing}"
               Text="Testing"
               Grid.Row="1"
               VerticalOptions="CenterAndExpand"
               HorizontalOptions="CenterAndExpand" />

</Grid>
</ContentView>

我在另一个页面视图模型中设置数据

第二页视图模型

m_ScanPageViewModel.Testing = true; `setting in constructor`

这没有约束力。

我在这里错过了什么?

标签: c#xamarin.forms

解决方案


当您使用 MVVMCross 时,您可以简单地更新您的属性,例如...

private bool _myProperty;
public bool MyProperty
{
    get => _myProperty;
    set
    {
        _myProperty = value;
        RaisePropertyChanged(() => MyProperty);
        // take any additional actions here which are required when MyProperty is updated
    }
}

https://www.mvvmcross.com/documentation/fundamentals/data-binding

注意:- 确保为所有ViewModel继承MvxViewModel

https://www.mvvmcross.com/documentation/fundamentals/viewmodel-lifecycle


推荐阅读