您的位置:首页 > 其它

边看书边做边发挥-图书软件-2

2016-03-02 00:25 309 查看
同样 Chapter 类像 Catalogue 类引用相同的空间实现相同的模式,只是成员包含一个 Sections 小节集合的属性

public class Chapter : INotifyPropertyChanged
{
private ObservableCollection<Chapter> sections = new ObservableCollection<Chapter>();

public Chapter()
{

}

public ObservableCollection<Chapter> Sections
{
get { return sections; }
set { SetProperty(ref sections, value); }
}

...其他成员...
}


Section 类也实现相同的模式,但成员包含一个 NestSection 属性,表示嵌套小节,用自包含的方式可以无限嵌套,默认 NestSection 属性是空的,他没有嵌套任何 NestSection 对象。开始我想使用 Section 属性名,但却发现编译错误,成员名不能与它们的封闭类型相同,类型不是自身类型也不能,我倒是很想用和类型相同的属性名。

public class Section : INotifyPropertyChanged
{
private Section nestSection;

public Section()
{

}

public Section NestSection
{
get { return nestSection; }
set { SetProperty(ref nestSection, value); }
}
...其他成员...
}


现在发现 FrameworkDesignGuidelines 子空间没任何用处,我只需要一个FrameworkDesignGuidelinesBook 类,把这个文件夹删除。新建一个 FrameworkDesignGuidelinesBook 类表示这本框架设计规范的书,有一个 Catalogue 属性,表示这本书的目录,为了让这个类在 WPF 的界面中通过控件点击来生成一本书,实现和上面的类相同的模式。然后在构造函数初始化 Catalogue 属性并填充这本书的目录数据。

现在有一个问题,Catalogue 类应该是一个集合类,可以添加条目,条目的类型是 Section 类,所以,现在要改造一下Catalogue 类,让他从 ObservableCollection 类派生,这样就可以有父类的功能,可以添加项,也实现了通知机制,而 Catalogue 类的成员保持不变,INotifyPropertyChanged 接口也是多余了,因为 ObservableCollection 类已经实现这个接口,PropertyChanged 事件移除。同样,chapters 字段也是多余的,基类的基类 Collection 类有管理这些对象的 Items 内部字段,使用这个段表示 chapters 字段,泛型参数为 Chapter 类,因为要管理 Chapter 对象,现在改造的代码如下

public class Catalogue : ObservableCollection<Chapter>
{
public Catalogue()
{

}

protected void SetProperty<T>(ref T item, T value,
[CallerMemberName]string propertyName = null){..}
}


辅助方法 OnPropertyChanged() 也不用保留了,基类有相同的实现,但 SetProperty() 方法可以保留,方便调用,而不使用 OnPropertyChanged() 方法来变更属性,应该使用 SetProperty() 方法更方便。

FrameworkDesignGuidelinesBook 类的 catalogue 字段可以添加条目了,这本书有9章,所以需要添加9项。

public class FrameworkDesignGuidelinesBook : INotifyPropertyChanged
{
private Catalogue catalogue= new Catalogue();

public FrameworkDesignGuidelinesBook()
{
catalogue.Add(new Chapter());
catalogue.Add(new Chapter());
catalogue.Add(new Chapter());
catalogue.Add(new Chapter());
catalogue.Add(new Chapter());
catalogue.Add(new Chapter());
catalogue.Add(new Chapter());
catalogue.Add(new Chapter());
catalogue.Add(new Chapter());
}

public Catalogue Catalogue
{
get { return catalogue; }
set { SetProperty(ref catalogue, value); }
}

...其他成员...
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  net 图书