【问题标题】:Xamarin Forms `ContentView` Binding Does not workXamarin Forms`ContentView`绑定不起作用
【发布时间】:2023-03-24 10:32:01
【问题描述】:

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

使用 MVVM 跨插件进行绑定。

PageViewModel

public class ScanPageViewModel : BasePageViewModel
    {
        private bool m_testing;


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

ContentView 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`

这没有约束力。

我在这里错过了什么?

【问题讨论】:

  • 您的属性测试应该通知 OnPropertyChanged!
  • @FreakyAli 这可能是作为 MVVM Cross 的Set 方法的一部分完成的。
  • 你能告诉我你做了什么吗?
  • 我尝试过同样的事情,但它的工作原理。我认为你从另一个页面设置了这个值,然后在另一个页面中查看该值。

标签: c# xamarin.forms


【解决方案1】:

当您使用 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

注意:- 确保为您的所有 ViewModels

继承 MvxViewModel

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    • 2020-08-29
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    相关资源
    最近更新 更多