I am new to WPF, and suffering with an existing code.
We have a tree, which has many branches/leaves. In one branch we have a DataGrid.
If we click on the empty area of the grid (where no rows are), then TreeView.SelectedItemChanged called properly. In our case, SelectedItem = 'SelectedGridBorder' (see XAML below)
But if we click on a row/cell of the grid, row gets focused, but TreeView.SelectedItemChanged is NOT called. So TreeView.SelectedItem is still the previously selected item. Is is possible to achieve this (according to me) logical behavior, so when clicking on a row, TreeView.SelectedItemChanged should be called automatically, and TreeView.SelectedItem should be 'SelectedGridBorder', just like clicking on the grid area where no rows are.
Why is it different for 'SelectedItemChanged' to click on a grid row, or click on a grid where no rows are?
Thanks.
XAML:
<TreeView x:Name="CalculationDataTree" .....>
<Cinch:EventCommander.Mappings>
<Cinch:CommandEvent
Command="{Binding Path=DataContext.SelectionChangeCommand ....
Event="SelectedItemChanged"
Cinch:CommandEvent.CommandParameter="{Binding ElementName=CalculationDataTree,Path=SelectedItem}"/>
...
<TreeViewItem x:Name="Params" ...>
<TreeViewItem.Header>
<TextBlock>Parameters</TextBlock>
</TreeViewItem.Header>
<TreeViewItem x:Name="Dates" Margin="0,6,0,0">
<TreeViewItem.Header>
<StackPanel Orientation="Horizontal">
<TextBlock Margin="4,10">Date(s)</TextBlock>
<ContentControl Margin="4,6" Content="{Binding}" ContentTemplate="{StaticResource OwnEditorTemplate}" />
</StackPanel>
</TreeViewItem.Header>
</TreeViewItem>
<Border Name="SelectedGridBorder" ... >
<StackPanel Orientation="Vertical">
<TextBlock Margin="4,10">Other parameters</TextBlock>
<StackPanel Orientation="Horizontal">
<DockPanel>
<dg:DataGrid Height="300" Width="600" Name="dataGrid" ....>
<dg:DataGrid.Columns>
...
</dg:DataGrid.Columns>
The answer to
Why is it different for 'SelectedItemChanged' to click on a grid row, or click on a grid where no rows are?
MouseDown is a bubbling event. What's happening is the TextBox of your DataGrid marked the event as handled so it never reached TreeViewItem (WPF creates the TreeViewItem automatically even though you didn't specifically include it in your markup). If you clicked on a Header, or RowSelector, they would not mark the event as handled.
To get the behavior you were expecting
//WPF creates the TreeViewItem automatically if you didn't include it
<TreeViewItem PreviewMouseDown="TreeviewItem_PreviewMouseDown">
<Border Name="SelectedGridBorder" ... >
<StackPanel Orientation="Vertical">
<TextBlock Margin="4,10">Other parameters</TextBlock>
<StackPanel Orientation="Horizontal">
The Handler
private void TreeviewItem_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
var treeViewItem = sender as TreeViewItem;
treeViewItem.IsSelected = true;
}