PropertyChanged在将TextBox绑定到空属性并且该属性变为null时未触发。

huangapple go评论57阅读模式
英文:

PropertyChanged not raised when TextBox bound to a null property becomes null

问题

I have this field and property

private long? _defautID;
public long? DefautID
{
    get => _defautID;
    set
    {
        if (_defautID != value)
        {
            _defautID = value;
            OnPropertyChanged();
        }
    }
}

与一个文本框关联

<TextBox Content="{Binding 
                   Path=Expertise.DefautID, UpdateSourceTrigger=PropertyChanged}"/>

当我从文本框中添加或删除数字时,我的属性会更新,PropertyChanged 会正常触发。

但是当我删除最后一个数字,使文本框变为空时,我的属性不会更新(它保留最后已知的值),因此 PropertyChanged 不会触发。

这种行为有什么原因吗?是否有解决方法?

PropertyChanged 的实现:

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

I have this field and property

private long? _defautID;
public long? DefautID
{
    get => _defautID;
    set
    {
        if (_defautID != value)
        {
            _defautID = value;
            OnPropertyChanged();
        }
    }
}

linked to a textbox

<TextBox Content="{Binding 
                   Path=Expertise.DefautID, UpdateSourceTrigger=PropertyChanged}"/>

When I add or remove a digit from the textbox, my property is updated and PropertyChanged is triggered without any problem.

But when I remove the last digit and my textbox becomes empty, my property is not updated (it keeps the last known value) and thus PropertyChanged is not triggered.

Is there any reason for this behavior ? And is there a workaround ?

PropertyChanged implementation :

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

答案1

得分: 3

设置绑定的 TargetNullValue 属性:

<TextBox Text="{Binding 
    Path=Expertise.DefautID, UpdateSourceTrigger=PropertyChanged, TargetNullValue=''}"/>

这是为了使 TextBox 中的空字符串成功转换为 default(long?) 并设置您的属性。

英文:

Set the TargetNullValue property of the binding:

<TextBox Text="{Binding 
    Path=Expertise.DefautID, UpdateSourceTrigger=PropertyChanged, TargetNullValue=''}"/>

This is required for the emtpy string in the TextBox to be successfully converted to default(long?) and for your property to be set.

huangapple
  • 本文由 发表于 2023年5月24日 22:21:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76324575.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定