0
votes

I have a wpf window that displays tasks. The user clicks on a task in a TreeView control then other controls (TextBox, ComboBox, etc.) shows the various properties of the selected task. I have implemented this as follows:

1) The TreeView is pupulated by:

ItemsSource="{Binding Source={StaticResource cvsTasks}}"

2) The DataContext for the window is set in code-behind as follows:

Public Class Tasks
Private tsk As Task
....
Private Sub LoadMe(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
  DataContext = tsk
....
End Sub 

Private Sub SelectTask(sender As Object, e As RoutedPropertyChangedEventArgs(Of Object)) Handles treTasks.SelectedItemChanged
  tsk = DirectCast(e.NewValue, Task)
End Sub
....
End Class

3) Each of the task properties use binding as shown below for the Description property:

<TextBox
    x:Name="txtDescription"
    AcceptsReturn="True"
    Text="{Binding Path=Description}">
</TextBox>

and that is what is not working. None of the controls with binding show corresponding value when a TreeView item is selected by the user.

What an I doing wrong?

3

3 Answers

0
votes

Setting the private tsk field won't cause the view to refresh. Try to set the DataContext property in your event handler:

Private Sub SelectTask(sender As Object, e As RoutedPropertyChangedEventArgs(Of Object)) Handles treTasks.SelectedItemChanged
  DataContext = DirectCast(e.NewValue, Task)
End Sub

Or make tsk a public property that you bind to and raise the PropertyChanged event for. This requires you to implement the INotifyPropertyChanged interface.

0
votes

Please add Mode and UpdateSourceTrigger in your XAML.

Text="{Binding Path=Description,  Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
0
votes

You can achieve this using ElementName.

Consider this is your TreeView control

<TreeView x:Name="myTreeView" ItemsSource="{Binding Source={StaticResource cvsTasks}}">
    ...
</TreeView>

Then, binding at your TextBox will be like,

<TextBox Text="{Binding ElementName=myTreeView, Path=SelectedItem.Description, Mode=TwoWay}"
         AcceptsReturn="True"/>