(WPF VB.Net)如何获取嵌套在TreeView中的Checkbox的状态?

时间:2010-11-18 19:56:29

标签: wpf vb.net treeview checkbox

我有一个带有TreeView的WPF窗口,其中包含每个节点的复选框。我希望能够捕获复选框的状态,但我不知道如何。 (我试图在没有用XML编写大量代码的情况下这样做)

以下是我在XML中的内容:

<TreeView Grid.Column="1" Grid.ColumnSpan="3" Grid.Row="1" Height="200" HorizontalAlignment="Left" Margin="126,299,0,0" Name="TreeView1" VerticalAlignment="Top" Width="220" ItemsSource="{Binding}" DataContext="{Binding}">
</TreeView> 

在VB代码中:

Dim site As ELSite
Dim sites() As ELSite

Dim parentCheckbox = New CheckBox
Dim parentNode = New TreeViewItem

parentCheckbox.Content = "All Sites"
parentNode.Header = parentCheckbox

For Each osite In sites
 Dim childNode = New TreeViewItem
 Dim childCheckbox = New CheckBox
 childCheckbox.Content = osite.SiteName.ToString
 childNode.Header = childCheckbox
 parentNode.Items.Add(childNode)
Next

TreeView1.Items.Add(parentNode)

Private Sub TreeView1_SelectedItemChanged(ByVal sender As System.Object, ByVal e As System.Windows.RoutedPropertyChangedEventArgs(Of System.Object)) Handles TreeView1.SelectedItemChanged

'This event doesn't seem to occur when I check or uncheck a checkbox

End Sub

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

...
For Each osite In sites
   Dim childNode = New TreeViewItem
   Dim childCheckbox = New CheckBox

   ' add this to your code '
   AddHandler childCheckBox.Checked, AddressOf chkbox_Checked
   AddHandler childCheckBox.Unchecked, AddressOf chkbox_Unchecked
   '-----------------------'

   childCheckbox.Content = osite.SiteName.ToString
   childNode.Header = childCheckbox
   parentNode.Items.Add(childNode)
Next
...


Private Sub chkbox_Checked(ByVal sender As Object, ByVal e As RoutedEventArgs)
    Dim chk = DirectCast(sender, CheckBox)
    ' Do whatever needs to be done when chk has been checked '
End Sub

Private Sub chkbox_Unchecked(ByVal sender As Object, ByVal e As RoutedEventArgs)
    Dim chk = DirectCast(sender, CheckBox)
    ' Do whatever needs to be done when chk has been unchecked '
End Sub