英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论