views:

485

answers:

1

When databinding the Treeview in the Silverlight Toolkit to a data source, how do you then access the TreeViewItem itself to use its IsEnabled property? Or do we lose that functionality and need to support it with any custom hierarchicaldatatemplate?

If I'm databinding to a tree of custom objects, how do I then access an individual TreeViewItem to set IsEnabled? Ideally, I want to do this via databinding. I'm wondering if using ItemContainerStyle would work? I think I'm getting a little confused at the relationship between ItemContainerStyle, ItemTemplate, etc. Obviously the TreeViewItem is created for us when we databind to plain old objects, but how do we set its properties, in particular with binding?

+3  A: 

The real problem is that you cannot set bindings on the TreeViewItem that is automatically created for each databound object using XAML.

The various ItemsControls, including TreeView, let you override the creation of the item, such as ListBoxItem, TreeViewItem, etc. You can set bindings for properties on those items in code.

Public Class MyTreeView Inherits TreeView

Protected Overrides Sub PrepareContainerForItemOverride(ByVal element As System.Windows.DependencyObject, ByVal item As Object)

    MyBase.PrepareContainerForItemOverride(element, item)

    Dim tvi As TreeViewItem = element
    Dim bindIsEnabled As New Binding("IsEnabled")
    bindIsEnabled.Mode = BindingMode.OneWay
    tvi.SetBinding(TreeViewItem.IsEnabledProperty, bindIsEnabled)

End Sub

Credit goes to the ComboBox example at http://www.fret1.com/blog/silverlight-data-binding-enableddisabled-items-on-combobox/

Pete