本文整理汇总了C#中System.Windows.Controls.TreeViewItem类的典型用法代码示例。如果您正苦于以下问题:C# TreeViewItem类的具体用法?C# TreeViewItem怎么用?C# TreeViewItem使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
TreeViewItem类属于System.Windows.Controls命名空间,在下文中一共展示了TreeViewItem类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Window_Loaded
private void Window_Loaded(object sender, RoutedEventArgs e)
{
try
{
foreach (DriveInfo driveInfo in DriveInfo.GetDrives())
{
TreeViewItem item = new TreeViewItem();
item.Header = driveInfo.Name;
MessageBox.Show((string)item.Header);
if (driveInfo.IsReady)
{
DirectoryInfo dirInfo = new DirectoryInfo(driveInfo.Name);
foreach (DirectoryInfo di in dirInfo.GetDirectories())
{
item.Items.Add(new TreeViewItem() { Header = di.Name });
}
foreach (FileInfo fi in dirInfo.GetFiles())
{
item.Items.Add(new TreeViewItem() { Header = fi.Name });
}
}
this.treeView1.Items.Add(item);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
示例2: LoadTree
//这里也是分两步,第一步创建一个Header的DataTemplate,第二步每一个Header都添加这个这个DataTemplate
private void LoadTree()
{
DataTemplate template = GetTreeHeaderDataTemplate();
TreeViewItem AsianItem=new TreeViewItem();
AsianItem.Header = "亚洲";
AsianItem.HeaderTemplate = template;
TreeViewItem EuropeItem=new TreeViewItem();
EuropeItem.Header = "欧洲";
EuropeItem.HeaderTemplate = template;
TreeViewItem chinaItem=new TreeViewItem();
chinaItem.Header = "中国";
chinaItem.HeaderTemplate = template;
TreeViewItem japnaItem = new TreeViewItem();
japnaItem.Header = "日本";
japnaItem.HeaderTemplate = template;
TreeViewItem ukItem = new TreeViewItem();
ukItem.Header = "英国";
ukItem.HeaderTemplate = template;
TreeViewItem denmarkItem = new TreeViewItem();
denmarkItem.Header = "丹麦";
denmarkItem.HeaderTemplate = template;
AsianItem.Items.Add(chinaItem);
AsianItem.Items.Add(japnaItem);
EuropeItem.Items.Add(ukItem);
EuropeItem.Items.Add(denmarkItem);
this.MainTreeView.Items.Add(AsianItem);
this.MainTreeView.Items.Add(EuropeItem);
}
示例3: BuildConfictSet
private void BuildConfictSet(FunctionConflictSet conflictSet, TreeViewItem item, int setIndex)
{
if (conflictSet == null || item == null)
return;
StringBuilder headerBuidller = new StringBuilder();
headerBuidller.Append("Конфликтный набор №{0}. ");
headerBuidller.Append("Функция ");
headerBuidller.Append(conflictSet.FunctionType.ToString());
headerBuidller.Append(".");
TreeViewItem setItem = new TreeViewItem();
setItem.Header = String.Format(headerBuidller.ToString(), setIndex);
item.Items.Add(setItem);
conflictSet.Reset();
while (conflictSet.ClosedEx == false)
{
FunctionGenerationInfo info = conflictSet.CurrentFunction;
headerBuidller.Clear();
headerBuidller.Append("Функция \"{0}\". ");
headerBuidller.Append("Коэффициент релевантности: {1}.");
TreeViewItem functionItem = new TreeViewItem();
functionItem.Header = String.Format(headerBuidller.ToString(), info.Function.Name, info.RelevanceLevel);
setItem.Items.Add(functionItem);
conflictSet.NextEx();
}
conflictSet.Reset();
}
示例4: FillLayers
private void FillLayers(ItemsControl root)
{
foreach (var dwgLayer in dwgDocument.GetLayers())
{
var layerItem = new TreeViewItem
{
Header = dwgLayer.Name
};
FillEntities(layerItem, dwgLayer);
root.Items.Add(layerItem);
// Помещаем в таблицу соответствующий слой при его выделении в дереве
var dwgLayerCopy = dwgLayer;
layerItem.Selected += delegate(object sender, RoutedEventArgs args)
{
// Отсеиваем маршрутизируемые события от дочерних узлов
if (layerItem.Equals(args.Source) && propertyGrid != null)
propertyGrid.SelectedObject = dwgLayerCopy;
};
// Повторяем в дереве изменения значений имен слоев в таблице
dwgLayerCopy.NameChanged += (sender, newName) => layerItem.Header = newName;
}
}
示例5: Save
public static TreeStatus Save(TreeViewItem treeViewItem)
{
if (treeViewItem == null) return null;
TreeStatus status = new TreeStatus(treeViewItem);
SaveStatus(treeViewItem, status);
return status;
}
示例6: pageTreeViewItem_DoubleClick
void pageTreeViewItem_DoubleClick(object sender, MouseButtonEventArgs eventArgs) {
LOG.Debug("spaceTreeViewItem_MouseLeftButtonDown is called!");
TreeViewItem clickedItem = eventArgs.Source as TreeViewItem;
if (clickedItem ==null) {
return;
}
Confluence.Page page = clickedItem.Tag as Confluence.Page;
if (page == null) {
return;
}
if (!clickedItem.HasItems) {
LOG.Debug("Loading pages for page: " + page.Title);
(new Thread(() => {
Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)(() => {ShowBusy.Visibility = Visibility.Visible;}));
List<Confluence.Page> pages = confluenceConnector.getPageChildren(page);
Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)(() => {
foreach(Confluence.Page childPage in pages) {
LOG.Debug("Adding page: " + childPage.Title);
TreeViewItem pageTreeViewItem = new TreeViewItem();
pageTreeViewItem.Header = childPage.Title;
pageTreeViewItem.Tag = childPage;
clickedItem.Items.Add(pageTreeViewItem);
pageTreeViewItem.PreviewMouseDoubleClick += new MouseButtonEventHandler(pageTreeViewItem_DoubleClick);
pageTreeViewItem.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(pageTreeViewItem_Click);
}
ShowBusy.Visibility = Visibility.Collapsed;
}));
}
) { Name = "Loading childpages for confluence page " + page.Title }).Start();
}
}
示例7: addLicFileToTree
private void addLicFileToTree(string filename, bool fileExists = true)
{
TreeViewItem RootItem = new TreeViewItem();
RootItem.IsExpanded = true;
RootItem.Tag = filename;
string rootItemName = filename.Split('\\').Last();
RootItem.Header = rootItemName;
if (fileExists)
{
LicFile file = new LicFile(rootItemName, filename);
foreach (Product p in file.Products)
{
TreeViewItem product = new TreeViewItem();
product.Header = p.ID + ": " + p.currUsersNum + " of " + p.maxUsersNum + " users.";
product.IsExpanded = false;
foreach (User u in p.Users)
{
product.Items.Add(u.Name);
}
RootItem.Items.Add(product);
}
}
else
{
TreeViewItem notFoundReport = new TreeViewItem();
notFoundReport.Header = "Файл не найден";
RootItem.Items.Add(notFoundReport);
}
treeView.Items.Add(RootItem);
fileNames.AddMonitorFileName(filename);
}
示例8: WalkTreeViewItem
public static bool WalkTreeViewItem(TreeView tree, TreeViewItem treeViewItem, object selectedValue)
{
if (treeViewItem.DataContext == selectedValue)
{
treeViewItem.SetValue(TreeViewItem.IsSelectedProperty, true);
treeViewItem.Focus();
treeViewItem.BringIntoView();
return true;
}
var itemsHostProperty = treeViewItem.GetType().GetProperty("ItemsHost", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
var itemsHost = itemsHostProperty?.GetValue(treeViewItem, null) as Panel;
if (itemsHost == null)
{
return false;
}
foreach (var item in itemsHost.Children.OfType<TreeViewItem>())
{
var oldExpanded = item.IsExpanded;
item.IsExpanded = true;
item.UpdateLayout();
if (WalkTreeViewItem(tree, item, selectedValue))
{
return true;
}
item.IsExpanded = oldExpanded;
}
return false;
}
示例9: ViewLog_Load
private void ViewLog_Load(object sender, EventArgs e)
{
_xmlDoc.Load("log.xml");
XmlNodeList nodes = _xmlDoc.GetElementsByTagName("date");
TreeViewLog.Items.Clear();
TreeViewItem core = new TreeViewItem();
core.Header = "log";
List<TreeViewItem> firstLevel = new List<TreeViewItem>();
int n = 0;
foreach (XmlNode node in nodes)
{
firstLevel.Add(new TreeViewItem());
firstLevel[n].Header = node.Attributes["id"].Value;
List<TreeViewItem> secondLevel = new List<TreeViewItem>();
int k=0;
foreach (XmlNode m in node.ChildNodes)
{
string str = m.Attributes["name"].Value + " " + m.Attributes["status"].Value;
secondLevel.Add(new TreeViewItem());
secondLevel[k].Header = str;
firstLevel[n].Items.Add(secondLevel[k]);
k++;
}
core.Items.Add(firstLevel[n]);
n++;
}
TreeViewLog.Items.Add(core);
}
示例10: HandleTreeViewItemVisibleChanged
/// <summary>
/// Handles the TreeView item visible changed.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="DependencyPropertyChangedEventArgs" /> instance containing the event data.</param>
private void HandleTreeViewItemVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var selectedItem = sender as TreeViewItem;
// whenever a TreeViewItem becomes visible re-calculate its sub-items
if (selectedItem != null && selectedItem.IsVisible)
{
var dump = selectedItem.DataContext as IObjectDump;
if (dump != null)
{
// remove old sub-items
foreach (TreeViewItem oldSubItem in selectedItem.Items)
{
oldSubItem.IsVisibleChanged -= HandleTreeViewItemVisibleChanged;
}
selectedItem.Items.Clear();
// add new sub-items for public fields, properties and enumerable members
foreach (IObjectDump subItemDump in dump.PublicFields.Union(dump.Properties).Union(dump.EnumerableMembers))
{
var newSubItem = new TreeViewItem {Header = subItemDump.ObjectName, DataContext = subItemDump};
newSubItem.IsVisibleChanged += HandleTreeViewItemVisibleChanged;
selectedItem.Items.Add(newSubItem);
}
}
}
}
示例11: GetNew
public TreeViewItem[] GetNew()
{
ArrayList r = new ArrayList(ForgeNew.Length);
TreeViewItem t = new TreeViewItem();
foreach (ForgeVersion Forge in ForgeNew)
{
if (Forge.installer == null)
{
continue;
}
if (t.Header == null)
{
t.Header = Forge.mcver;
}
if (t.Header.ToString() != Forge.mcver)
{
t = new TreeViewItem();
r.Add(t);
}
if (ForgeDownloadUrl.ContainsKey(Forge.vername))
ForgeDownloadUrl[Forge.vername] = Forge.installer[1];
else
ForgeDownloadUrl.Add(Forge.vername, Forge.installer[1]);
if (ForgeChangeLogUrl.ContainsKey(Forge.vername))
ForgeChangeLogUrl[Forge.vername] = Forge.installer[1];
else
ForgeChangeLogUrl.Add(Forge.vername, Forge.changelog);
t.Items.Add(Forge.vername);
Logger.log("获取Forge"+Forge.vername);
}
return r.ToArray(typeof(TreeViewItem)) as TreeViewItem[];
}
示例12: FindNode
private TreeViewItem FindNode(TreeViewItem parentNode, ItemCollection nodes, string directory, int attemptNumber = 1)
{
if (attemptNumber < 1)
throw new ArgumentOutOfRangeException("attemptNumber", attemptNumber, "attemptNumber must be >= 1");
if (attemptNumber > 2)
{
return parentNode;
}
List<TreeViewItem> childNodes = new List<TreeViewItem>();
foreach (TreeViewItem childNode in nodes)
{
childNodes.Add(childNode);
DirectoryTreeNode dirNode = childNode as DirectoryTreeNode;
if (dirNode == null)
continue;
if (string.Compare(dirNode.Directory, directory, true) == 0)
{
return dirNode;
}
}
UpdateNodeChildren((DirectoryTreeNode)parentNode);
TreeViewItem node = FindNode(parentNode, parentNode.Items, directory, attemptNumber + 1);
return node;
}
示例13: button_Click
//private static void ProcessNode(HtmlNode node, Stack<HtmlNode> stack)
//{
// var depth = stack.Count;
// var padding = String.Empty.PadLeft(depth, ' ');
// stack.Push(node);
// try
// {
// Debug.WriteLine(padding + "Node: " + node.Name);
// foreach (var child in node.ChildNodes)
// {
// ProcessNode(child, stack);
// }
// }
// finally
// {
// stack.Pop();
// }
//}
private void button_Click(object sender, RoutedEventArgs e)
{
using (var stream = File.OpenRead(@"C:\Documents\bookmarks_7_27_15.html"))
{
var doc = new HtmlDocument();
doc.Load(stream);
var rootFolder = new Folder { Name = "<root>" };
ProcessNode(doc.DocumentNode, rootFolder);
if (rootFolder.Folders.Count == 1)
rootFolder = rootFolder.Folders.Single();
treeView.Items.Add(GetTree(rootFolder));
var bookmarks = rootFolder.AllBookmarks.ToList();
bookmarks.Sort(
(l, r) => StringComparer.OrdinalIgnoreCase.Compare(l.Href.ToString(), r.Href.ToString()));
var lookupItem = new TreeViewItem { Header = "Lookup" };
var lookup = rootFolder.AllBookmarks.ToLookup(b => b.Href.ToString(), b => b.Folder, StringComparer.OrdinalIgnoreCase);
foreach (var key in lookup)
{
var folders = new HashSet<string>(key.Select(k => k.FullName), StringComparer.OrdinalIgnoreCase);
if (folders.Count > 1)
{
//folders.Sort((l, r) => StringComparer.OrdinalIgnoreCase.Compare(l.FullName, r.FullName));
var keyItem = new TreeViewItem { Header = key.Key + " (" + folders.Count + ")" };
foreach (var folder in folders.OrderBy(f => f, StringComparer.OrdinalIgnoreCase))
keyItem.Items.Add(new TreeViewItem { Header = folder });
lookupItem.Items.Add(keyItem);
}
}
lookupItem.ExpandSubtree();
treeView.Items.Add(lookupItem);
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var bookmark in rootFolder.AllBookmarks)
set.Add(bookmark.ToString());
foreach (var txt in set)
Debug.WriteLine(txt);
using (var output = File.OpenWrite(@"C:\Documents\output.html"))
{
output.SetLength(0);
using (var writer = new StreamWriter(output))
{
writer.WriteLine(@"<!DOCTYPE NETSCAPE-Bookmark-file-1>");
writer.WriteLine(@"<!-- This is an automatically generated file.");
writer.WriteLine(@" It will be read and overwritten.");
writer.WriteLine(@" DO NOT EDIT! -->");
writer.WriteLine(
"<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html;charset=UTF-8\">");
writer.WriteLine(@"<TITLE>Bookmarks</TITLE>");
WriteFolder(rootFolder, writer, new HashSet<string>(StringComparer.OrdinalIgnoreCase), "");
}
}
//Debugger.Break();
}
}
示例14: ProcessElement
private void ProcessElement(DependencyObject element, TreeViewItem previousItem)
{
// Create a TreeViewItem for the current element
TreeViewItem item = new TreeViewItem();
item.Header = element.GetType().Name;
item.IsExpanded = true;
// Check whether this item should be added to the root of the tree
//(if it's the first item), or nested under another item.
if (previousItem == null)
{
treeElements.Items.Add(item);
}
else
{
previousItem.Items.Add(item);
}
// Check if this element contains other elements
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
{
// Process each contained element recursively
ProcessElement(VisualTreeHelper.GetChild(element, i), item);
}
}
示例15: MainWindow
public MainWindow()
{
this.InitializeComponent();
treeitem = new List<TreeViewItem>();
entityproperty = new EntityProperty();
entityproperty.Name = myThumb1.Title;
ent = new TreeViewItem();
ent.Header = entityproperty.Name;
treeitem.Add(ent);
treeView1.ItemsSource = treeitem;
// Insert code required on object creation below this point.
}