當前位置:成語大全網 - 書法字典 - WPF的TreeView可以通過數據庫動態添加、修改和刪除節點。

WPF的TreeView可以通過數據庫動態添加、修改和刪除節點。

只需在表中創建三個字段(ID、Name、ParentID),然後定義壹個對應於該節點的類,例如:

公共類類型節點

{

公共字符串ID { get設置;}

公共字符串名稱{ get設置;}

公共TypeNode父級{ get設置;}

公共可觀察集合<。TypeNode & gtChildren { get設置;}

public bool IsSelected { get設置;}

}

增加構造節點的方法,根據ID確定父節點和子節點,代碼不列;然後實現INotifyPropertyChanged接口,這幾乎是相同的。然後定義幾種樣式:

& ltstyle x:Key =“TypeTreeStyle“target type =“TreeView“& gt。

& ltsetter Property =“Template“& gt;

& lt二傳手。值& gt

& ltcontrol template target type =“TreeView“& gt。

& ltscroll viewer Padding =“4“Focusable =“False“CanContentScroll =“False“& gt。

& ltitems presenter/& gt;

& lt/scroll viewer & gt;

& lt/ControlTemplate>

& lt/Setter。值& gt

& lt/Setter & gt;

& lt/Style & gt;

& ltstyle x:Key =“type node“target type =“treeview item“& gt。

& ltsetter Property =“is selected“Value =“{ Binding is selected,Mode = two way }“/& gt;

& ltsetter Property =“font weight“Value =“Normal“/& gt。

& lt風格。觸發器& gt

& lttrigger Property =“is selected“Value =“True“& gt;

& ltsetter Property =“font weight“Value =“Bold“/& gt。

& lt/Trigger & gt;

& lt/風格。觸發器& gt

& lt/Style & gt;

& lthierarchical data template x:Key =“type tree group“items source =“{ Binding Children }“& gt;

& ltText block Text =“{ Binding TypeName }“font size =“13“/& gt。

& lt/hierarchical data template & gt;

定義壹個可觀察集合

& ltTreeView items source =“{綁定類型樹}”

style =“{ static resource type tree style }”

ItemContainerStyle =“{ static resource type node }“

item template =“{ static resource type tree group }“/& gt;

根據節點的IsSelected屬性,確定創建子節點的位置,同時獲取數據的ParentID,並將創建時指定的ID和名稱存儲在數據庫中,完成。希望對妳有幫助。如果您有任何問題,請提問或Hi。