-1

I have a treeview:

<TreeView>
  <TreeView.ItemTemplate>
    <HierarchicalDataTemplate ItemsSource="{Binding Path=TucActivity}">
      <TextBlock>
        <TextBlock.Text>
          <MultiBinding StringFormat="{}{0} {1}">
            <Binding Path="DisplayedStartTime"></Binding>
            <Binding Path="Name"></Binding>
          </MultiBinding>
        </TextBlock.Text>
      </TextBlock> 
      <HierarchicalDataTemplate.ItemTemplate>
        <DataTemplate>
          <TextBlock Text="{Binding Path=Message}" />
        </DataTemplate>
      </HierarchicalDataTemplate.ItemTemplate>
    </HierarchicalDataTemplate>
  </TreeView.ItemTemplate>
</TreeView>

bounded to Observable Collection object:

MainTreeView.ItemsSource = ((App)Application.Current).TucOC;

I want that every time the ((App)Application.Current).TucOC is updated the selected item (and also the focus) will be the one in the observable collection.

I would like to do it in one place since the ((App)Application.Current).TucOC is updated in multiple places in the code.

What's the best option to do it?

Em1
  • 1,077
  • 18
  • 38
kaycee
  • 1,199
  • 4
  • 24
  • 42
  • this question is answered multiple times [HERE](http://stackoverflow.com/questions/7153813/wpf-mvvm-treeview-selecteditem) and also [HERE](http://stackoverflow.com/questions/1000040/selecteditem-in-a-wpf-treeview) – WiiMaxx Jun 20 '13 at 07:52

1 Answers1

-6

If you're using a development pattern like MVVM, I would create a property on your ViewModel class that's of the type held in the ObservableCollection, to hold the currently selected item for your treeview source. That would look something like this:

private object _selectedTuc;
public object SelectedTuc
{
    get
    {
        return _selectedTuc;
    }
    set
    {
        _selectedTuc = value;
        OnPropertyChanged("SelectedTuc");
    }
}

Then, in your treeview, you bind this property to the treeview's SelectedItem:

<TreeView ItemsSource="{Binding TucOC, Mode=OneWay}" SelectedItem="{Binding SelectedTuc, Mode=TwoWay}">...</TreeView>

Notice on the binding for SelectedItem you specify a Mode value of TwoWay - this allows for your SelectedTuc property to be updated from the UI, as well as the UI being updated whenever the SelectedTuc property changes.

If you're not using MVVM or something like it, you're going to need to create a utility method that will update the TreeView's SelectedItem every time the selected item or index in your ObservableCollection changes. This is not, however, the way I would recommend doing it.

jpb
  • 79
  • 4
  • 2
    How did you get around this error: 'SelectedItem' property is read-only and cannot be set from markup. – Bob Horn Feb 04 '12 at 03:27