当文本框中未填充任何内容时,将 mvvm WPF 中的属性设置为 null [英] Set null to property in mvvm WPF when nothing is filled in textbox
问题描述
我实现了一个文本框,它绑定到一个视图模型.例如,我将文本框默认填写为100",但如果我将其更改为 10,则该属性始终设置正确.但是当我删除所有数字时,我希望该属性设置为空.但它只是在什么都没有填写时不设置值.他只是保留最后一个值..
I implemented a textbox, and this binds to a viewmodel. I fill in the textbox default by '100' for example, but if i change this to 10, the property always sets correctly. But when i delete all the numbers, i want that the property is set to null. But it just don't set the value when nothing is filled in. He just keeps the last value..
这是我的代码,viewmodel + xaml:
this is my code , viewmodel + xaml:
public double MaxTime
{
get
{
return maxTime;
}
set
{
maxTime = value;
OnPropertyChanged("MaxTime");
if (SelectedQuestionDropList != null)
{
foreach (QuestionCluster cluster in this.Examination.QuestionClusters)
{
if (cluster == SelectedQuestionDropList)
{
cluster.MaxTime = value;
}
}
}
}
}
<TextBox Height="23"
Visibility="{Binding Path=VisibleClusterDetails, Converter={StaticResource boolToVis},UpdateSourceTrigger=PropertyChanged}"
Text="{Binding Path=MaxTime,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"
HorizontalAlignment="Right" Margin="0,511,601,0" Name="textBox2"
VerticalAlignment="Top" Width="120" />
推荐答案
您的属性是双精度值,因此它不支持 null 或空值.
Your property is a double so it won't support null or empty values.
这里不使用双精度值,而是将属性作为字符串公开,并在属性 getter 和 setter 中在字符串和双精度值之间转换.在 setter 中,我可以根据需要处理空值或空值,并且可以轻松处理所需的任何特殊格式.
Instead of using a double here I would expose the property as a string and convert between string and double in my property getter and setter. In the setter I could handle null or empty values as I wanted, and I could easily handle any special formatting that was needed.
这篇关于当文本框中未填充任何内容时,将 mvvm WPF 中的属性设置为 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!