.NET Maui DataBinding 不更新条目或标签

问题描述 投票:0回答:1

您好,我正在尝试在 .NET Maui 中使用数据绑定,但遇到了一个奇怪的问题

我有一个 Entry,我希望用户在按下 ViewModel 中的按钮时能够清除它。

当我按下按钮清除 Customer.CustomerName 时,属性不会更新,直到我导航到应用程序中的另一个页面。

我不明白为什么当属性已经实现 INotifyPropertyChanged 时它不更新

XAML

<Entry 
    Grid.Row="1"
    Grid.ColumnSpan="2"
    FontAttributes="Bold"
    FontSize="Large"
    HorizontalTextAlignment="Center"
    Placeholder="Name"
    Text="{Binding CurrentCustomer.CustomerName}"
    VerticalTextAlignment="Center" />
<Button 
    Grid.Row="7"
    Grid.Column="0"
    Margin="2"
    Command="{Binding ClearUserInfo}"
    Text="Clear User Information" />

<!--  Test to show reset value  -->
<Label
    Grid.Row="7"
    Grid.Column="1"
    Margin="2"
    Text="{Binding CurrentCustomer.CustomerName}" />

视图模型

[AddINotifyPropertyChangedInterface]
public class CustomerViewModel
{     
    public Customer CurrentCustomer { get; set; } = new Customer();

    public ICommand ClearUserInfo =>
       new Command(() =>
       {
           ClearUserInputs();        
       });

    private void ClearUserInputs()
    {
        CurrentCustomer.CustomerName = "Set string to empty";
        // CurrentCustomer.CustomerName = string.Empty;
    }
}
public class Customer
{
    public int CustomerId { get; set; }
    public string CustomerName { get; set; }
    public string CustomerAddress { get; set; }
    public string CustomerPhone { get; set; }
    public string Email { get; set; }
}
data-binding maui
1个回答
0
投票

您需要使您的

Customer
模型可观察,或者您也可以为
CurrentCustomer
分配新值。

子属性不会仅仅因为父属性被用作可观察属性而变得可观察。相反,每个应该可观察的属性都必须调用

PropertyChanged
接口的
INotifyPropertyChanged
事件,用 Fody 术语来说,这将如下所示:

[AddINotifyPropertyChangedInterface]
public class Customer
{
    public int CustomerId { get; set; }
    public string CustomerName { get; set; }
    public string CustomerAddress { get; set; }
    public string CustomerPhone { get; set; }
    public string Email { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.