Wpf 如何将PreviewMouseDown绑定到ItemsControl中的FormattedText

Wpf 如何将PreviewMouseDown绑定到ItemsControl中的FormattedText,wpf,xaml,mvvm,itemscontrol,Wpf,Xaml,Mvvm,Itemscontrol,在使用MVVM的WPF中,我希望在单击鼠标时将视图模型中的属性设置为显示的文本。也就是说,我希望ItemsControl中的PreviewMouseDown事件在viewmodel中设置一个属性 在下面的XAML中,我使用ItemsControl显示FormattedText ObservableCollection中的字符串。下面的XAML显示格式化文本,一切都很顺利 但是,如何将PreviewMouseDown绑定到视图模型的每个生成项 我在ItemsControl中使用DataTempla

在使用MVVM的WPF中,我希望在单击鼠标时将视图模型中的属性设置为显示的文本。也就是说,我希望ItemsControl中的PreviewMouseDown事件在viewmodel中设置一个属性

在下面的XAML中,我使用ItemsControl显示FormattedText ObservableCollection中的字符串。下面的XAML显示格式化文本,一切都很顺利

但是,如何将PreviewMouseDown绑定到视图模型的每个生成项

我在ItemsControl中使用DataTemplate的所有尝试最终都会导致:

System.Windows.Data错误:26:已为ItemsControl容器类型的项忽略ItemTemplate和ItemTemplateSelector

XAML

对画布定义的修改不会导致调用该命令,并且我无法将其添加到DataTemplate中


感谢任何帮助或更好的想法。

由于ItemsControl中的项目托管在ContentPresenter中,因此如果您将命令绑定到同一个项目,它将应用于ItemsControl中的项目

因此,我们可以在ItemsControl或任何父容器的资源中使用ContentPresenter的通用样式

乙二醇


上面的示例基于这样的假设,即PreviewMouseDown命令位于每个项目的视图模型中,如果该命令位于父视图模型中,则您可能会使用

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

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