【问题标题】:Entry is not Clearing with Bindable Property条目未使用可绑定属性清除
【发布时间】:2023-03-25 21:28:01
【问题描述】:

我的 2 个条目是从可绑定属性绑定的,并且运行良好,但是在保存条目中的数据后,我想清除条目值,但这无法影响我的 UI,如果 ii 使用 ctrl+ 在我的 xaml 文件上保存 onproperty触发更改事件并清除条目。我还在我的可绑定属性中使用了一个类,其中包含两个 get set 变量。如果我为两个条目创建单独的两个不同的可绑定属性,则它可以工作,但在一个类中它不起作用。但我只想将单个可绑定属性与类一起使用。我正在分享我的代码。

//Inotify 类

public class BaseViewModel : INotifyPropertyChanged
{
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
else
{
return;
}
}
}

// 模型类

public class NoModel
{
public string No { get; set; }
public string Amt { get; set; }
}

//关于属性更改事件

public NoModel bindNoModel= new NoModel ();

public NoModel BindNoModel
{
get { return bindNoModel; }
set
{
bindNoModel= value;
OnPropertyChanged(nameof(BindNoModel));
}
}

//我的xaml代码

    <StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand">
        <Label WidthRequest="110" Text="Amount" VerticalOptions="Center" Font="Bold" FontSize="Medium" ></Label>
        <Entry Text="{Binding BindNoModel.Amt }" Placeholder="Enter Amount" ReturnType="Done"  ReturnCommand="{Binding SubmitCommand}" Keyboard="Numeric" HorizontalOptions="FillAndExpand" />
    </StackLayout>

//关于保存命令

BindNoModel.No = string.Empty;
BindNoModel.Amt = string.Empty;

注意 1:上面的 save 命令代码不起作用,我在我的 xaml 文件上使用 ctrl +save 然后 UI 更改。

注意 2:如果我创建不同的属性,下面的代码可以工作

public string no;
public string No
{
    get { return no; }
    set
    {
        no = value;
        OnPropertyChanged(nameof(No));
    }
}
public string amt ;
public string Amt
{
get { return amt ; }
set
{
amt = value;
OnPropertyChanged(nameof(Amt ));
}
}

//关于保存命令

No = string.Empty;
Amt = string.Empty;

【问题讨论】:

  • 您的NoModel 应该继承INotifyPropertyChanged 并实现PropertyChanged 处理程序。注 2 是在 NoModel 类中定义属性的正确方法。我希望 Ctrl + Save 重新加载 UI 是否处于 Debug 模式,这是 HotReload Xamarin 中的一项最新功能。
  • 如果我使用 Note-2 方法,那么如果我有 10 个条目,那么我必须创建 10 个属性更改事件。
  • 不,只有一个 OnPropertyChangedEvent,您可以放置​​一个断点并进行 switch-case 检查以查看正在更改的属性

标签: xamarin xamarin.forms


【解决方案1】:

在您最初的问题中,在保存命令中,您正在更改属性 BindNoModel.NoBindNoModel.Amt 的值,而不是 BindNoModel,因此不会触发 OnPropertyChanged(nameof(BindNoModel))

你可以在save命令中重置BindNoModel来达到你想要的效果:

public void save() {

    BindNoModel = new NoModel() {Amt = string.Empty };

}

在您的 Note2 中,您正在更改 BindNoModel.NoBindNoModel.Amy 的值,然后将触发 OnPropertyChanged(nameof(No));OnPropertyChanged(nameof(Amy));,因此条目的值发生了变化:

public void save() {

    BindNoModel.No = string.Empty;
    BindNoModel.Amt = string.Empty;
}

sample project 已上传,有任何问题欢迎随时问我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    相关资源
    最近更新 更多