Reputation: 5394
I'm new to this and can't quit get the correct syntax. This works correctly to capture the Left Mouse click
on the textbox within the treeview:
<HierarchicalDataTemplate
DataType="{x:Type r:NetworkViewModel}"
ItemsSource="{Binding Children}"
>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding NetworkIP}" Width="110" >
<TextBlock.InputBindings>
<MouseBinding MouseAction="LeftClick"
Command="{Binding DataContext.SelectItem, RelativeSource={RelativeSource FindAncestor, AncestorType=TreeView}}"
CommandParameter="{Binding}" />
</TextBlock.InputBindings>
</TextBlock>
</StackPanel>
</HierarchicalDataTemplate>
How can this be done using a Style
block in the Resources
?
The goal being to use the same style for all TextBoxes
in the TreeView
. Something that would sit in the Usercontrol.Resources
and be refrenced by the HierarchicalDataTemplate
.
Upvotes: 1
Views: 656
Reputation: 13204
If I understand you correctly, you could define a template in the controls or windows resources with a target type (opposed to key x:Key=...
) to have it automatically applied to all items in the tree view.
Here is a small example with a definition of a template in the window resources, which contains the InputBindings
definition. This template will be automatically applied to all objects of type ItemViewModel
if no other template is explicitly defined by the ItemsControl
or TreeView
. In this example, the items are displayed in a simple ItemsControl
but it works for the TreeView
just the same.
Note that for this to work, all items in the TreeView
need to be of the same type. It is not sufficient if they are derived from the same base type. The template will only be applied, if the type defined in Template.DataType
is exactly the same as the type of the ViewModel. If your TreeViews ItemsScource
s contain mixed type, you would need to specify the template for every type separately.
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="clr-namespace:WpfApplication2"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate DataType="{x:Type loc:ItemViewModel}">
<TextBlock Text="{Binding Name}" Width="110" >
<TextBlock.InputBindings>
<MouseBinding
MouseAction="LeftClick"
Command="{Binding SelectItem}" />
</TextBlock.InputBindings>
</TextBlock>
</DataTemplate>
</Window.Resources>
<Grid>
<ItemsControl ItemsSource="{Binding Items}" />
</Grid>
</Window>
Upvotes: 1