0
votes

In WPF using MVVM I would like to set a property in the view model to the displayed text when the mouse is clicked. That is I want the PreviewMouseDown event from the ItemsControl to set a property in the viewmodel.

In the following XAML, I am using an ItemsControl to display Strings from a FormattedText ObservableCollection. All goes well with the XAML below to display the FormattedText.

But, how can I bind a PreviewMouseDown to each of the generated items for the view model?

All my attempts to use DataTemplate within the ItemsControl ultimately lead to:

System.Windows.Data Error: 26 : ItemTemplate and ItemTemplateSelector are ignored for items already of the ItemsControl's container type;

XAML

<ItemsControl 
         ItemsSource="{Binding Strings}" >
        <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <Canvas 
                             Background="Transparent"
                             Width="{x:Static h:Constants.widthCanvas}" 
                             Height="{x:Static h:Constants.heightCanvas}" 
                             />
                    </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
</ItemsControl>

Adding

 h:MouseBehaviour.PreviewMouseDownCommand="{Binding PreviewMouseDown}"

to the Canvas definition never results in the command being called and I can't add it in a DataTemplate.

Any help or better idea is appreciated.

1

1 Answers

1
votes

as items in an ItemsControl are hosted in ContentPresenter so if you bind your command to the same it will be applied to the Item's in the ItemsControl

so for that purpose we can use a generic Style for ContentPresenter in the resources of ItemsControl or any parent container

eg

    <Style TargetType="ContentPresenter">
        <Setter Property="h:MouseBehaviour.PreviewMouseDownCommand"
                Value="{Binding PreviewMouseDown}" />
    </Style>

above example is based on assumption that PreviewMouseDown command is in the view model for each item, if the command is in the parent view model then you may perhaps use

    <Style TargetType="ContentPresenter">
        <Setter Property="h:MouseBehaviour.PreviewMouseDownCommand"
                Value="{Binding PreviewMouseDown, RelativeSource={RelativeSource FindAncestor,AncestorType=ItemsControl}}" />
    </Style>