C# 依赖属性/属性强制
我有以下课程:
public class Numbers :INotifyPropertyChanged
{
private double _Max;
public double Max
{
get
{
return this._Max;
}
set
{
if (value >= _Min)
{
this._Max = value;
this.NotifyPropertyChanged("Max");
}
}
}
private double _Min;
public double Min
{
get
{
return this._Min;
}
set
{
if (value <= Max)
{
this._Min = value;
this.NotifyPropertyChanged("Min");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (this.PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
问题:我不想允许用户输入小于最小值的最大值等等。但是,当最小/最大值的默认值为零时,当其他类尝试设置最小/最大值时,上面的代码第一次不起作用。 由于默认情况下最小值和最大值将为零,因此如果设置最小值 > 0 逻辑上是正确的,但约束不允许这样做。 我想我需要使用依赖属性或强制来解决这个问题。有人可以指导这样做吗?
I have the following class:
public class Numbers :INotifyPropertyChanged
{
private double _Max;
public double Max
{
get
{
return this._Max;
}
set
{
if (value >= _Min)
{
this._Max = value;
this.NotifyPropertyChanged("Max");
}
}
}
private double _Min;
public double Min
{
get
{
return this._Min;
}
set
{
if (value <= Max)
{
this._Min = value;
this.NotifyPropertyChanged("Min");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (this.PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
Problem: I dont want to allow user to enter max value less than min value and so on. But above code is not working for the first time when other class try to set min / max value when min / max value has default value of zero.
Since by default min and max value will be zero, if min value is set > 0 which is logically correct but the constraint is not allowed to do that.
I think I need to solve this using dependent property or coercion. Could anyone guide to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将 _Max 初始化为 Double.MaxValue,将 _Min 初始化为 Double.MinValue。
Initialize _Max to Double.MaxValue, _Min to Double.MinValue.
你可以用 Nullable 支持它,所以它变成这样:
You could back it by a Nullable so it becomes this:
我不知道我是否理解正确,但您可以有一个
private bool
指示该值是否是第一次设置,从而覆盖检查。从我的脑海中浮现出来:
I don't know if i understand you correctly, but you could have a
private bool
indicating if the value is getting set for the first time and thus overriding the check.out of my head: