Привет, ребята, моя конечная цель - создать выбираемый файловый браузер, используя представление Tree в WPF. У меня было правильное отображение дерева, и я решил перейти к соответствующей структуре MVVM, и древовидное представление не будет отображаться. Я провел некоторое исследование и увидел, что мне нужно использовать HierarchicalDataTemplates со связыванием, чтобы он работал. Я просто смущен тем, как иметь рекурсивные функции, возвращающие сложные каталоги с помощью HierarchialDataTemplate (children).File Browser Tree View MVVM
В настоящее время я использую тип TreeView для контейнера верхнего уровня для древовидного вида в виртуальной машине. Ниже мой ViewModel с рекурсивными функциями, чтобы пройти через каталог. (Если есть более простой способ сделать это, не стесняйтесь, дайте мне знать, это была моя первая попытка :)).
public void onBrowseCommand (object commandInvoker)
{
Microsoft.Win32.OpenFileDialog win = new Microsoft.Win32.OpenFileDialog();
Nullable<bool> result = win.ShowDialog();
if (result == true)
{
string filename = win.FileName;
rootfile= filename;
rootfile = filename;
int index = rootfile.Length;
index = index - 4;
rootfile = rootfile.Remove(index);
//Get file version for text box
var fversion = FileVersionInfo.GetVersionInfo(filename);
version = fversion.FileVersion;
//get date created
DateTime fdate = File.GetCreationTime(filename);
date = fdate.ToString();
//Display Folder Contents
showzip(filename);
Window_Loaded();
}
}
private void showzip(string path)
{
try
{
bool isZip = path.Contains(".zip");
if (isZip)
{
dynamic shellApplication = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"));
dynamic compressedFolderContents = shellApplication.NameSpace(path).Items;
string destinationPath = System.IO.Directory.GetParent(path).FullName;
dynamic destinationFolder = shellApplication.NameSpace(destinationPath);
destinationFolder.CopyHere(compressedFolderContents);
}
}
catch (Exception ex)
{
throw ex;
}
}
private void Window_Loaded()
{
string dir = rootfile;
TreeViewItem items = new TreeViewItem();
items.Header = dir.Substring(dir.LastIndexOf('\\') + 1);
items.Tag = dir;
items.FontWeight = FontWeights.Normal;
fillFiles(items, dir);
foreach (string s in Directory.EnumerateDirectories(dir))
{
TreeViewItem item = new TreeViewItem();
item.Header = s.Substring(s.LastIndexOf('\\') + 1);
item.Tag = s;
item.FontWeight = FontWeights.Normal;
fillFiles(item, s);
FillTreeView(item, s);
items.Items.Add(item);
}
foldersItem.Items.Add(items);
}
private void FillTreeView(TreeViewItem parentItem, string path)
{
foreach (string str in Directory.EnumerateDirectories(path))
{
TreeViewItem item = new TreeViewItem();
item.Header = str.Substring(str.LastIndexOf('\\') + 1);
item.Tag = str;
item.FontWeight = FontWeights.Normal;
parentItem.Items.Add(item);
fillFiles(item, str);
FillTreeView(item, str);
}
}
private void fillFiles(TreeViewItem parentItem, string path)
{
foreach (string str in Directory.EnumerateFiles(path))
{
TreeViewItem item = new TreeViewItem();
item.Header = str.Substring(str.LastIndexOf('\\') + 1);
item.Tag = str;
item.FontWeight = FontWeights.Normal;
parentItem.Items.Add(item);
}
}
Вот мой XAML тоже. Спасибо, просто нужно толчок, если не толчок в правильном направлении.
<TreeView DockPanel.Dock="Left" Margin="5,0,5,5" x:Name="foldersItem" ItemsSource="{Binding foldersItem}" >
</TreeView>
У меня есть простой класс, который имеет имя, путь к файлу и метод. Для этого мне нужно создать классы, содержащие как папки, так и файлы? –
Да, если вы пытаетесь сделать MVVM, вам понадобятся классы, которые представляют ваши объекты. У этой ссылки есть несколько разных примеров, которые могут вам помочь: http://www.codeproject.com/Articles/26288/Simplifying-the-WPF-TreeView-by-the-the-the-W- ViewMode – Locke
Я все еще не могу показать дерево. –