I.Introduction
TreeView có lẽ là một cái tên khá quen thuộc với các bạn, TreeView được sử dụng nhiều trong các ứng dụng từ Web cho đến Windows….
Trong bày này mình xin chia sẻ cách sử dụng TreeView trong WPF
II.Creating Project And Coding
Mở Visual Studio 2010 lên và tạo WPF Application
chúng ta có thể Kéo thả TreeView từ ToolBox trực tiếp vào giao diện, hay có thể thêm vào từ code XAML.
Các bạn sẽ hiểu rõ hơn ở đoạn code XAML sau :
1: <Window x:Class="TreeView.MainWindow"
2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4: Title="MainWindow" Height="350" Width="525">
5: <Grid>
6: <TreeView Name="treeView" Foreground="Black">
7: <TreeView.Background>
8: <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
9: <GradientStop Color="White" Offset="0" />
10: <GradientStop Color="White" Offset="1" />
11: <GradientStop Color="#FF979EC7" Offset="0.517" />
12: </LinearGradientBrush>
13: </TreeView.Background>
14: <TreeViewItem Header="Employee">
15: <TreeViewItem Header="Employee1"></TreeViewItem>
16: <TreeViewItem Header="Employee2"></TreeViewItem>
17: <TreeViewItem Header="Employee3"></TreeViewItem>
18: </TreeViewItem>
19: <TreeViewItem Header="CheckBox">
20: <CheckBox Content="CheckBox 1"/>
21: <CheckBox Content="CheckBox 2"/>
22: <CheckBox Content="CheckBox 3"/>
23: </TreeViewItem>
24: <TreeViewItem Header="Radio Button">
25: <RadioButton Content="Radio Button 1"/>
26: <RadioButton Content="Radio Button 2"/>
27: <RadioButton Content="Radio Button 3"/>
28: </TreeViewItem>
29: </TreeView>
30: </Grid>
31: </Window>
Về mặt ứng dụng, sau khi các bạn đã thêm một TreeView trong XAML, thì các bạn có thể dễ dàng add vào nó những TreeViewItem, trùy theo nhu cầu mà trong những TreeViewItem này các bạn Add thêm những Control mà mình thích.
Trong 1 TreeView có thể có nhiều TreeViewItem
1: <TreeView>
2: <TreeViewItem Header="Tên Nhóm Item1"/>
3: <TreeViewItem Header="Tên Nhóm Item2"/>/>
4: <TreeViewItem Header="Tên Nhóm Item3"/>/>
5: <TreeView>
Ngoài ra trong một TreeViewItem lại có thể chứa nhiều TreeViewItem hay Control khác
1: <TreeViewItem Header="Employee">
2: <TreeViewItem Header="Employee1"></TreeViewItem>
3: <TreeViewItem Header="Employee2"></TreeViewItem>
4: <TreeViewItem Header="Employee3"></TreeViewItem>
5: </TreeViewItem>
6: <TreeViewItem Header="CheckBox">
7: <CheckBox Content="CheckBox 1"/>
8: <CheckBox Content="CheckBox 2"/>
9: <CheckBox Content="CheckBox 3"/>
10: </TreeViewItem>
Bây giờ chúng ta chạy ứng dụng (Ctrl + F5) và xem kết quả
/*Life Run On Code*/