【问题标题】:Xamarin Data BindingXamarin 数据绑定
【发布时间】:2017-05-05 18:59:22
【问题描述】:

我真的不知道我是不是白痴,我要做的就是这么简单!

我有一个带有公共用户名字段的 ViewModel。

最初我试图让条目显示一个初始值,但在进一步查看后我发现我什至无法让视图更新视图模型。

我希望文本在我单击按钮时反映输入的用户名并将其显示在警报中。

我的视图模型:

public class LoginViewModel
{
    public String Username { get; set; }
    public String Password { get; set; }
    public int UserId { get; set; }
}

我的页面:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage Padding="15,15,15,15" 
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
xmlns:sys="clr-namespace:System;assembly=mscorlib"
x:Class="EngineerApp.LoginPage">
<AbsoluteLayout>
<StackLayout VerticalOptions="EndAndExpand" Orientation="Vertical">
    <Image Source="traklogo.png" VerticalOptions="FillAndExpand"></Image>
    <Label TextColor="#207cad" Text="Username" />
    <Label Text="{Binding Username}"></Label>
    <Entry Text="{Binding Username, Mode=TwoWay}" TextColor="Black" Placeholder="Please enter your username..." x:Name="txtUsername" />
</StackLayout>
</AbsoluteLayout>
</ContentPage>

我的页面代码:

public partial class LoginPage : ContentPage
{

    public LoginViewModel viewModel = new LoginViewModel();

    public LoginPage()
    {
        InitializeComponent();
        BindingContext = viewModel;

        btnLogIn.Clicked += delegate
        {
            DisplayAlert("Test",viewModel.Username,"Okay");
            return;

        };

    }
}

【问题讨论】:

  • INotifyPropertyChanged的实现在哪里?通常 OnPropertyChanged 会在 setter 中被调用。
  • 您好,很抱歉我实际上删除了它,因为我认为它不是必需的。相应更新。
  • Label 上的绑定就在 Entry 之前,暗示您确实需要它。数据绑定需要INotifyPropertyChanged 来驱动魔法。

标签: c# xaml xamarin data-binding


【解决方案1】:

来自实现INotifyPropertyChanged 的 LoginViewModel 的这个工作 sn-p 位于商店中发布的应用中:

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public string Username
    {
        get { return username; }
        set
        {
            if (username == value) return;
            username = value?.ToLowerInvariant();
            OnPropertyChanged();
        }
    }

以及相关联的EntryXAML sn-p:

          <Entry x:Name="UsernameEntry" HeightRequest="45" Keyboard="Email"
                Placeholder="{Binding LabelUsername}" Text="{Binding Username}">

【讨论】:

  • 为什么需要实现接口? Xamarin 默认不会绑定数据吗?
  • 不,INPC 是 Binding 函数依赖于知道模型/视图模型已更改的机制。没有它,用户界面将永远不知道何时更新自身。
  • 我不是在尝试更新 UI,而是在尝试从视图模型中读取数据。
  • 如果你只关心这个,试试 OneWayToSource 而不是 TwoWay
  • 但是,如果您不使用 INPC,您的标签将永远不会更新
【解决方案2】:

我已经解决了。此页面之前的页面正在传递它自己的 BindingContext。删除它解决了我的问题。

【讨论】:

    猜你喜欢
    • 2018-09-25
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    • 2016-11-24
    • 2016-09-08
    • 2019-07-13
    • 2016-06-26
    • 2021-04-18
    相关资源
    最近更新 更多