If you're inclined to maintain that design then I would go with a solution like the following:
public static int MinimumLength
{
get { return _MinimumLength; }
set
{
if (_MinimumLength != value)
{
_MinimumLength = value;
OnGlobalPropertyChanged("MinimumLength");
}
}
}
static event PropertyChangedEventHandler GlobalPropertyChanged = delegate { };
static void OnGlobalPropertyChanged(string propertyName)
{
GlobalPropertyChanged(
typeof (ExampleClass),
new PropertyChangedEventArgs(propertyName));
}
public ExampleClass()
{
// This should use a weak event handler instead of normal handler
GlobalPropertyChanged += this.HandleGlobalPropertyChanged;
}
void HandleGlobalPropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "MinimumLength":
if (length > MinimumLength)
length = MinimumLength;
break;
}
}
This is pretty much equivalent to maintaining a list of instances but I find it more maintainable and clearer. Also, you really need to use a weak event handler strategy, otherwise, your instances will not be garbage collected because they will always be associated with the static event which acts like a GC root.
You can read more about weak event handlers in the following blog posts (which were written by me so I'm biased):
.NET Weak Event Handlers – Part I
.NET Weak Event Handlers – Part I
In an unrelated note your code is currently firing property changed when in fact the property value did not change. For example:
- Set MinimumLength to 5;
- Set length to 10; (event fires since the value changes from the default 0 to 5)
- Set length to 11; (event fires but it should not since the length is still 5)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…