【发布时间】:2011-05-12 10:10:52
【问题描述】:
在我的 Silverlight 4 项目中,我有一个实现接口的简单类,例如:
public interface IMyClass
{
string Name { get; set; }
anyotherclass Value { get; set; }
}
父类包含一组 IMyClass 元素,例如:
public class ParentClass
{
ObservableCollection<IMyClass> Children { get; }
}
现在我想确保 IMyClass.Name 在 Children 集合中是唯一的。用户可以更改 IMyClass.Name - 所以我需要验证名称是否已经在集合中。我想使用 Silverlight 异常和验证机制,我的 XAML 文本框看起来像:
<TextBox Text="{Binding
ValidatesOnExceptions=true,
NotifyOnValidationError=true,
Mode=TwoWay,
Path=Name}"/>
所以我需要检查 Name 属性的设置器,例如:
public string Name
{
get { return _name; }
set
{
if (value == _name)
return;
if (CollectionAlreadyContainsName(this, value))
throw new ArgumentException("The name already exists");
else
_name = value;
OnPropertyChanged("Name");
}
}
问题来了:CollectionAlreadyContainsName 需要知道集合,但在 IMyClass 对象中我不知道我在哪个集合中。我需要保留对父级的引用,例如
public interface IMyClass
{
string Name { get; set; }
anyotherclass Value { get; set; }
ParentClass Parent { get; }
}
由于交叉引用以及需要确保始终正确设置父级,这对我来说很糟糕。所以我寻找另一种方法来做到这一点。一个想法是让 ParentClass 监听 IMyClass 的 NameChanged 事件,并在必要时恢复名称更改。但这不适用于上述 Silverlight 异常和验证机制。
任何想法如何解决这个问题?
提前致谢,
弗兰克
【问题讨论】:
标签: c# silverlight validation binding