使用 Treeview 显示信息
Using a Treeview to display information
我有一个 treeview
,其中有一个国家列表,我还有一个 textbox
,其中包含关于每个国家的描述 如何根据单击的节点更改描述中的文本.
您可以订阅您的 TreeView
的 AfterSelect
活动:
public partial class Form1
{
private TreeView treeView1;
private TextBox textBox1;
// ... shortened example
public Form1()
{
InitializeComponent();
treeView1.AfterSelect += treeView1_AfterSelect;
//...
}
private void TreeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
string description = string.Empty;
TreeNode node = treeView1.SelectedNode;
if (node != null)
description = // determine the text from your country data
textBox1.Text = description;
}
}
我一般把TreeNode
的Tag
属性设置为对应的模型实例。所以如果你有一个 Country
class 这样的:
public class Country
{
public string Name { get; set; }
public string Description { get; set; }
}
我会这样添加 TreeNodes
:
Country country = new Country { Name = "SomeCountry", Description = "description" };
TreeNode nextNode = new TreeNode(country.Name);
nextNode.Tag = country;
parentNode.Nodes.Add(nextNode);
您的 AfterSelect
处理程序可能如下所示:
private void TreeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
textBox1.Text = (treeView1.SelectedNode?.Tag as Country)?.Description ?? string.Empty;
}
我有一个 treeview
,其中有一个国家列表,我还有一个 textbox
,其中包含关于每个国家的描述 如何根据单击的节点更改描述中的文本.
您可以订阅您的 TreeView
的 AfterSelect
活动:
public partial class Form1
{
private TreeView treeView1;
private TextBox textBox1;
// ... shortened example
public Form1()
{
InitializeComponent();
treeView1.AfterSelect += treeView1_AfterSelect;
//...
}
private void TreeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
string description = string.Empty;
TreeNode node = treeView1.SelectedNode;
if (node != null)
description = // determine the text from your country data
textBox1.Text = description;
}
}
我一般把TreeNode
的Tag
属性设置为对应的模型实例。所以如果你有一个 Country
class 这样的:
public class Country
{
public string Name { get; set; }
public string Description { get; set; }
}
我会这样添加 TreeNodes
:
Country country = new Country { Name = "SomeCountry", Description = "description" };
TreeNode nextNode = new TreeNode(country.Name);
nextNode.Tag = country;
parentNode.Nodes.Add(nextNode);
您的 AfterSelect
处理程序可能如下所示:
private void TreeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
textBox1.Text = (treeView1.SelectedNode?.Tag as Country)?.Description ?? string.Empty;
}