1. 语法
1.1. XAML
2. 备注
当前版本的TreeGrid仅可以使用甘特图控件指定数据源格式。如需支持其他类型数据源,需要重新实现AbstractExpander和AbstractTreeGridLayout。
2.1. 定义Expander样式
通过自定义AbstractExpander的集成类,并设置TreeGrid.ExpanderProvider,可实现Expander的自定义,从而更换逻辑或样式。
自定义类的实现可参考默认提供的Expander类:SimpleTaskExpander
TreeGrid是扩展Silverlight自身提供的DataGrid实现的,关键是自定义了新的Column类型,此Column在每一行的单元格中添加了一个按钮控件,根据任务的层级缩进,并在用户单击时,发起一个“展开/折叠”事件,事件EventArgs中包含行所对应的任务Item数据。
代码如下:
1: namespace V2TEK.Silverlight.Charts.TreeGridHelper
2: {
3: /// <summary>
4: /// 包含一个默认的Expander,继承自AbstractExpander。
5: /// 如有必要,可以通过继承AbstractExpander,复写Expander,并设置ExpanderProvider。
6: /// </summary>
7: public class TreeGridExpanderColumn : DataGridTextColumn
8: {
9: public TreeGridExpanderColumn()
10: {
11: }
12:
13: private AbstractExpander CreateExpander()
14: {
15: return Activator.CreateInstance(ExpanderProvider) as AbstractExpander;
16: }
17:
18: public Type ExpanderProvider
19: {
20: get;
21: set;
22: }
23:
24: protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
25: {
26: StackPanel panel = GeneratePanel(dataItem);
27: panel.Children.Add(base.GenerateEditingElement(cell, dataItem));
28: return panel;
29: }
30:
31: protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
32: {
33: StackPanel panel = GeneratePanel(dataItem);
34: panel.Children.Add(base.GenerateElement(cell, dataItem));
35: return panel;
36: }
37:
38: protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs)
39: {
40: TextBox ee = editingElement as TextBox;
41: if (ee == null)
42: {
43: return string.Empty;
44: }
45: string text = ee.Text;
46: int length = text.Length;
47: KeyEventArgs args = editingEventArgs as KeyEventArgs;
48: if ((args != null) && (args.Key == Key.F2))
49: {
50: ee.Select(length, length);
51: return text;
52: }
53: ee.Select(0, length);
54:
55: return base.PrepareCellForEdit(editingElement, editingEventArgs);
56: }
57:
58: public AbstractExpander GetExpander(DataGridRow row)
59: {
60: StackPanel panel = (StackPanel)this.GetCellContent(row);
61: AbstractExpander expander = panel.Children[0] as AbstractExpander;
62: expander.Data = row.DataContext;
63: return expander;
64: }
65:
66: private StackPanel GeneratePanel(object dataItem)
67: {
68: StackPanel panel = new StackPanel();
69: panel.Orientation = Orientation.Horizontal;
70: panel.Children.Add(GenerateExpander(dataItem));
71: return panel;
72: }
73:
74: private AbstractExpander GenerateExpander(object dataItem)
75: {
76: AbstractExpander expander = CreateExpander();
77: expander.Data = dataItem;
78: expander.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(expander_PropertyChanged);
79: return expander;
80: }
81:
82: void expander_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
83: {
84: if (e.PropertyName == AbstractExpander.DATA_PROPERTY)
85: (sender as AbstractExpander).Update();
86: }
87: }
88: }