【问题标题】:XAML view not updating when binding changes绑定更改时 XAML 视图未更新
【发布时间】:2020-02-06 17:01:14
【问题描述】:

我有一个绑定到 ViewModel 的 XAML 视图

当视图加载时,它将绑定上下文设置为一个对象(类型 GAME_TBL)

当 ViewModel 加载时,我等待带有唯一 ID 的消息到达

然后我用它来调用一个 API 并返回一个我转换的游戏对象来替换绑定的对象

然而,即使调试显示这一切正常,并且 PropertyChanged 触发,UI 永远不会更新

从视图:

<ContentPage.BindingContext>

    <viewmodels:VotingViewModel/>

</ContentPage.BindingContext>

.....

<Label Text="{Binding currentGame.GAME_NAME}" />

在 VotingViewModel 中:

public class VotingViewModel : BaseViewModel

{

    GAME_TBL gameSelected;

    public GAME_TBL currentGame
    {
        get {

            return _currentGame;


        }


        set
        {
            _currentGame = value;
            OnPropertyChanged(nameof(_currentGame));
        }
    }

    public VotingViewModel()
    {
        MessagingCenter.Subscribe<Views.GamesView, string>(this, "Selected Game", (sender, arg) =>

        {
            gameID = Convert.ToInt32(arg);

            currentGame = loadGameInfo(); // this interacts with an API to set object specifics

        });

    }

}

在 BaseViewModel 中

    protected virtual void OnPropertyChanged(
    string propertyName = null)
    {
        System.Diagnostics.Debug.WriteLine("Debug: Name of property: " + propertyName);

        PropertyChanged?.Invoke(this,
        new PropertyChangedEventArgs(propertyName));


    }

【问题讨论】:

  • nameof(_currentGame) 是内部支持字段,而不是您绑定到的公共属性
  • 哦,FFS,已经解决了。非常感谢
  • @Journeyman1234 你可以标记正确的答案,这将帮助更多有同样问题的人。
  • 我看不到怎么做,只有 cmets 显示为答案,而不是回复我的帖子?

标签: xamarin mvvm xamarin.forms


【解决方案1】:

您需要在 GAME_TBL 的 Model Class 中继承 BaseViewModel。在 GAME_TBL 类中,您需要按以下方式指定每个属性:

    private string _gAME_NAME;
    public string GAME_NAME
    {
        get => _gAME_NAME;
        set
        {
            _gAME_NAME = value;
            OnPropertyChanged(nameof(GAME_NAME));
        }
    }

每个属性都应该有一个内部支持属性,如上所述。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 2016-09-08
    • 2016-08-07
    • 2023-03-09
    • 2020-05-02
    相关资源
    最近更新 更多