【问题标题】:xamarin binding class propertyxamarin 绑定类属性
【发布时间】:2020-09-20 13:39:36
【问题描述】:

我正在尝试通过 xamarin 为 android 制作一个小应用程序。我也在尝试包含一些 MVVM。 我有一个模型类 UserInfoM(带有名称、密码……)。我有一个视图模型“mainpageVM”,我想在其中使用该类 UserInfoM 。这一直有效,直到某个点。当我在应用程序中输入内容时,会触发来自 UserInfoM(odel) 的 getter 和 setter。但我似乎无法在虚拟机中获取数据。这可能是一些明显的错误,但搜索了几天后,我似乎找不到答案。

在我的视图 (xaml) 中,我绑定到 Viewmodel 和

<ContentPage.BindingContext>
    <local:MainPageVM/>
</ContentPage.BindingContext>

...

    <Entry Grid.Row="2" Grid.Column="2" Grid.ColumnSpan="2" Placeholder="Enter Username"
           Text="{Binding UserInfo.User, Mode=TwoWay}"                
        >
        <Entry.BindingContext>
            <local:MainPageVM/>
        </Entry.BindingContext>

在我的 MainPageVM 中,使用 UserInfoM(odel) 作为属性:

    public UserInfoM UserInfo
    {
        get { return _userInfo ?? (_userInfo = new UserInfoM()); }
        set
        {
            _userInfo = value;
        }
    }

在我的 UserInfoM(odel) 中,我有以下属性(除其他外):

    private string user;
    public string User
    {
        get { return user; }
        set
        {
            if (user != value)
            {
                user = value;
                RaisePropertyChanged(nameof(User));
            }
        }
    }

所以 xaml 绑定似乎可以工作,因为触发了用户属性 getter 和 setter。但仅在模型中,虽然在视图中绑定设置为 MainPageVM。在 MainPageVM 中,所有模型属性都为空。它必须是某种逻辑错误,我没有收到错误,条目填写得很好,UserInfoM(odel)中的用户属性由条目字段填写(设置)但我不能访问/使用模型中的 UserInfo.User(或其他)属性。

简而言之,我可以绑定单个属性,但不能绑定来自另一个类的属性。我看了一堆教程并搜索了很多但找不到这个。 我希望解释足够清楚......任何帮助将不胜感激。 raiseproperty-method 实现了 INotifyPropertyChanged 并且非常适合单个属性。 de UserInfoM(odel) 中的用户属性已更新,但 Viewmodel 中的用户属性未更新。

【问题讨论】:

    标签: c# xamarin.forms binding derived-class


    【解决方案1】:

    您无需将 BindingContext 显式设置为您的条目。将绑定上下文设置到页面后,它将应用于其中的所有元素。你的Entry绑定是正确的,应该变成这样:

    <Entry Grid.Row="2" Grid.Column="2" Grid.ColumnSpan="2" Placeholder="Enter Username" 
        Text="{Binding UserInfo.User, Mode=TwoWay}">
    

    如果您像这样替换您的代码,Entry 将成功找到它的 BindingContext(从页面的那个),它会在其中查找 UserInfo 类,并将 UserInfo 的 User 属性绑定到 Entry 的 Text 属性。

    【讨论】:

    • 非常感谢!就这么简单。现在它似乎按预期工作了。
    • 很高兴它成功了!由于您是社区新手,当答案正确时,请用绿色复选标记标记,以便帮助其他人(他们会看到这个答案确实解决了您的问题)。 :)
    • 好的,完成。不知道绿色的复选标记。感谢您的提示,我会记住它的未来。
    猜你喜欢
    • 2018-05-06
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多