Мне удалось сделать это путем создания пользовательского ItemContainerStyle для TreeView . Вы должны быть в состоянии соединить это со следующими фрагментами кода.
1. Модель представления для TreeView
public class TreeViewModelView
{
public IEnumerable<object> Values
{
get { /* return hierarchical data source here ... */ }
}
/// <summary>
/// Command executed when the TreeViewItem expanding event is raised. The data item is passed in as a parameter.
/// </summary>
public RelayCommand<object> ExpandedCommand
{
get { return new RelayCommand<object>( o => MessageBox.Show( o.GetType().Name ) ); }
}
/// <summary>
/// Command executed when the TreeViewItem collapsing event is raised.
/// </summary>
public RelayCommand CollapsedCommand
{
get { return new RelayCommand( () => MessageBox.Show( "Collapsed" ) ); }
}
}
2. Определите TreeView и настройте необходимую привязку данных:
<TreeView x:Name="lstItems" HorizontalAlignment="Left" Margin="21,19,0,80" Width="283"
DataContext="{DynamicResource TreeViewModelView}"
ItemsSource="{Binding Values, Mode=OneWay}"
ItemTemplate="{DynamicResource TreeViewDataTemplate}"
ItemContainerStyle="{DynamicResource TreeViewItemStyle}">
<TreeView.Resources>
<mv:TreeViewModelView x:Key="TreeViewModelView" />
<HierarchicalDataTemplate x:Key="TreeViewDataTemplate" ItemsSource="{Binding Items}">
<Grid>
<TextBlock Text="{Binding Name}" />
</Grid>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
3. В Expression Blend вы можете создать редактировать копию ItemContainerStyle template
<Style x:Key="TreeViewItemStyle" TargetType="{x:Type TreeViewItem}">
...
</Style>
4. Затем замените ToggleButton на:
<ToggleButton x:Name="Expander" ClickMode="Press" IsChecked="{Binding IsExpanded, RelativeSource={RelativeSource TemplatedParent}}" Style="{StaticResource ExpandCollapseToggleStyle}">
<i:Interaction.Triggers>
<!-- When the Checked event is raised execute the ExpandedCommand with the data item as a parameter. -->
<i:EventTrigger EventName="Checked">
<GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding Path=DataContext.ExpandedCommand, RelativeSource={RelativeSource AncestorType={x:Type TreeView}}, Mode=OneWay}"
CommandParameter="{Binding}" />
</i:EventTrigger>
<!-- When the Unchecked event is raised execute the CollapsedCommand. -->
<i:EventTrigger EventName="Unchecked">
<GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding Path=DataContext.CollapsedCommand, RelativeSource={RelativeSource AncestorType={x:Type TreeView}}, Mode=OneWay}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ToggleButton>