如何在 [grand] 子节点中创建带有单选按钮的树视图? [英] How to create a treeview with radio buttons in the [grand]child nodes?

查看:75
本文介绍了如何在 [grand] 子节点中创建带有单选按钮的树视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个类似于以下内容的树视图:

I am trying to create a treeview that looks something like the following:

父母

|__Child1

|__ __ __ O Grandchild1

|__ __ __ O Grandchild1

|__ __ __ O Grandchild2

|__ __ __ O Grandchild2

|__Child2

|__ __ __ O Grandchild3

|__ __ __ O Grandchild3

|__ __ __ O Grandchild4

|__ __ __ O Grandchild4

我在 Visual Studio 2008 中使用 vb.net.非常感谢有关我如何实现这一点的任何见解!

I am using vb.net in Visual Studio 2008. Any insights as to how I can accomplish this will be very much appreciated!

推荐答案

在 TreeView 中不能有单选按钮,只能有复选框.

You cannot have radio buttons in a TreeView, only checkboxes.

一个解决方案是让复选框表现得像单选按钮:

A solution would be to make the checkboxes behave like radio buttons:

Private Sub TreeView1_AfterCheck(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterCheck
    If e.Node.Checked Then
        If e.Node.Level = 2 Then
            For Each node As TreeNode In e.Node.Parent.Nodes
                If node IsNot e.Node Then
                    node.Checked = False
                End If
            Next
        Else
            e.Node.Checked = False
        End If
    End If
End Sub

e.Node.Level = 2 检查确保只有孙节点的行为类似于单选按钮.

The e.Node.Level = 2 check makes sure only grandchild nodes behave like radio buttons.

将 TreeView 的 CheckBoxes 属性设置为 True 以启用复选框.

Set the TreeView's CheckBoxes property to True to enable checkboxes.

这是如何更改选定节点及其父节点的文本样式的示例:

This is an example of how to change text style of selected nodes and its parents:

Private Sub TreeView1_BeforeSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) Handles TreeView1.BeforeSelect
    If TreeView1.SelectedNode IsNot Nothing Then
        MakeSelected(TreeView1.SelectedNode, False)
    End If
    MakeSelected(e.Node, True)
End Sub

Private Sub MakeSelected(ByVal node As TreeNode, ByVal selected As Boolean)
    Dim SelectedFont As New Font(TreeView1.Font, FontStyle.Bold)
    node.NodeFont = IIf(selected, SelectedFont, TreeView1.Font)
    node.ForeColor = IIf(selected, Color.Blue, TreeView1.ForeColor)

    If node.Parent IsNot Nothing Then
        MakeSelected(node.Parent, selected)
    End If
End Sub

它会递归地更改所选节点及其父节点的文本样式,并在选择更改时将其设置回 TreeView 的默认样式.

It recursively changes the text style of the selected node and its parents and sets it back to the TreeView's default style when the selection changes.

这篇关于如何在 [grand] 子节点中创建带有单选按钮的树视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆