In WPF, we deal with different data types by defining different DataTemplate
s. In your case, you could already have defined some. If not, do so now, and in these DataTemplate
s, you can set the relevant ICommand
s. You can do this in several ways, but one easy way is just to define your content inside a 'blank' Button
:
<DataTemplate DataType="{x:Type YourDataTypePrefix:YourDataType}">
<Button Command="{Binding SomeCommand}">
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<!-- Define your YourDataType item content here -->
</Grid>
</ControlTemplate>
</Button.Template>
</Button>
</DataTemplate>
<DataTemplate DataType="{x:Type YourDataTypePrefix:OtherDataType}">
<Button Command="{Binding SomeOtherCommand}">
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<!-- Define your OtherDataType item content here -->
</Grid>
</ControlTemplate>
</Button.Template>
</Button>
</DataTemplate>
UPDATE >>>
That seems strange that you say you can't select the TreeViewItem
with that Button
. However, you could try using a ToggleButton
to bind to the TreeViewItem.IsSelected
property instead:
<ToggleButton Command="{Binding SomeCommand}" IsChecked="{Binding IsSelected,
RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}}}">
<ToggleButton.Template>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<!-- Define your YourDataType item content here -->
</Grid>
</ControlTemplate>
</ToggleButton.Template>
</ToggleButton>
If that still doesn't work, then use an AttachedProperty
to handle the PreviewMouseDown
event on a Grid
in the DataTemplate
s. You can find lots of online documentation about handling events with AttachedProperty
s, so I won't go over that again here. However, if you did that (and that is the better solution), then you could then do something like this:
<DataTemplate DataType="{x:Type YourDataTypePrefix:YourDataType}">
<Grid Attached:MouseEvents.PreviewMouseDown="{Binding SomeCommand}">
<!-- Define your YourDataType item content here -->
</Grid>
</DataTemplate>