Friday, August 8, 2008

Binding a WPF TreeView to an ObservableCollection

Here’s an example of Binding a WPF TreeView to an ObservableCollection to be able to dynamically add/remove items.  Not the xmlns:local= is set to the Namespace of your WPF project (intellisense will assist):

<Window x:Class="TreeTest"

  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

  xmlns:local="clr-namespace:CodeGen"

  Title="TreeTest" Height="300" Width="300">

    <Grid>

        <TreeView Margin="25,20,130,40" Name="TreeView1" ItemsSource="{x:Static local:TreeTest.BoatList}" >

            <TreeView.ItemTemplate>

                <DataTemplate>

                    <TextBlock Text="{Binding Path=Name}" />

                </DataTemplate>

            </TreeView.ItemTemplate>

        </TreeView>

        <Button Height="23" HorizontalAlignment="Right" Margin="0,50,26,0" Name="Button1" VerticalAlignment="Top" Width="75">Load Items</Button>

        <Button HorizontalAlignment="Right" Margin="0,113,26,126" Name="Button2" Width="75">Change Items</Button>

    </Grid>

</Window>

 

Imports System.Collections.ObjectModel

 

Partial Public Class TreeTest

 

    Public Shared BoatList As New ObservableCollection(Of Boat)

 

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click

        BoatList.Add(New Boat("FS 338", 19))

        BoatList.Add(New Boat("Hobie 16", 16))

    End Sub

 

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button2.Click

        Dim b As Boat = BoatList(0)

        BoatList.Remove(b)

        BoatList.Add(New Boat("Mad River Canoe", 17))

    End Sub

End Class

 

Public Class Boat

 

    Private _name As String

    Public Property Name() As String

        Get

            Return _name

        End Get

        Set(ByVal value As String)

            _name = value

        End Set

    End Property

 

    Private _length As Integer

    Public Property Length() As Integer

        Get

            Return _length

        End Get

        Set(ByVal value As Integer)

            _length = value

        End Set

    End Property

 

    Public Sub New(ByVal name As String, ByVal len As Integer)

        _name = name

        _length = len

    End Sub

 

End Class

 

 

 

2 comments:

Anonymous said...

Thanks, helped loads!

Paul said...

As simple as this example is, it helped me solve a problem that I'd been banging my head against for a couple of hours. Many thanks!