一樣的問題,在 Silverlight 的版本如何在 WPF 上實作呢?其實作法是一致的。
實作1
xaml
<Window x:Class="WpfTreeView1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TreeView Name="treeView1">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding SubFolders}">
<TextBlock TextWrapping="Wrap" Text="{Binding Name}"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
</Window>
cs
using System.Windows;
namespace WpfTreeView1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
treeView1.ItemsSource = FolderHelper.GetAllFolder();
}
}
}
執行結果如下圖: 實作2: 改用 Resource 讀取 Folder
在 cs 中,只有一行的程式 treeView1.ItemsSource = FolderHelper.GetAllFolder(); 實在不美觀。這裡使用在介紹的static binding小技巧,將這一行消除掉。
xaml
<Window x:Class="WpfTreeView1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WpfTreeView1="clr-namespace:WpfTreeView1" Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<WpfTreeView1:FolderHelper x:Key="helper" />
</Window.Resources>
<Grid>
<TreeView Name="treeView1" ItemsSource="{Binding Source={StaticResource ResourceKey=helper}, Path=AllFolders}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding SubFolders}">
<TextBlock TextWrapping="Wrap" Text="{Binding Name}"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
</Window>
cs
using System.Windows;
namespace WpfTreeView1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
當然,程式運作的結果是一致的。
程式碼下載
沒有留言:
張貼留言