c#依赖属性/属性强制转换
本文关键字:属性 转换 依赖 | 更新日期: 2023-09-27 18:10:39
我有以下类:
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));
}
}
问题:我不想让用户输入最大值小于最小值等等。但是,当其他类试图在min/max值默认值为零时设置min/max值时,上述代码第一次不起作用。由于默认情况下min和max值将为零,如果min值设置> 0,这在逻辑上是正确的,但约束不允许这样做。我想我需要用依赖性质或强制来解决这个问题。有人能指点一下吗?
初始化_Max为Double。MaxValue, _Min到Double.MinValue.
你可以用Nullable来支持它,这样它就变成了:
public class Numbers : INotifyPropertyChanged
{
private double? _Max;
public double Max
{
get
{
return _Max ?? 0;
}
set
{
if (value >= _Min || !_Max.HasValue)
{
this._Max = value;
this.NotifyPropertyChanged("Max");
}
}
}
private double? _Min;
public double Min
{
get
{
return this._Min ?? 0;
}
set
{
if (value <= Max || !_Min.HasValue)
{
this._Min = value;
this.NotifyPropertyChanged("Min");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (this.PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
我不知道我是否正确理解你,但你可以有一个private bool
指示如果值是第一次设置,从而覆盖检查。
out of my head:
private bool _FirstTimeSet = false;
private double _Max;
public double Max
{
get
{
return this._Max;
}
set
{
if (value >= _Min || _FirstTimeSet == false)
{
this._FirstTimeSet = true;
this._Max = value;
this.NotifyPropertyChanged("Max");
}
}
}