我正在使用prism
InvokeCommandAction
将Window.PreviewMouseDown
绑定到MainWindowViewModel
。然后,我有一个TabControl
,其ItemsSource
绑定到ObservableCollection<ItemViewModel>
,而TabControl.ContentTemplate
绑定到ItemViewModel.ItemContent
。
问题在于,当ItemViewModel.ItemContent
是/具有TextBox
并被单击时,MouseEventArgs.Source
是TabControl
。
我希望MouseEventArgs.Source
是TextBox
,这是我刚绑定到ContentControl.Content
外部的TabControl.ContentTemplate
时发生的情况。
下面是复制代码:
MainWindow.xaml
<Window
x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:WpfApp1"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:prism="http://prismlibrary.com/"
Title="MainWindow"
Width="800"
Height="450"
mc:Ignorable="d">
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<i:Interaction.Triggers>
<i:EventTrigger EventName="PreviewMouseDown">
<prism:InvokeCommandAction Command="{Binding PreviewMouseDownCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<StackPanel>
<ContentControl Content="{Binding SingleItemContent}" />
<TabControl ItemsSource="{Binding ItemViewModels}">
<TabControl.ContentTemplate>
<DataTemplate>
<ContentControl Content="{Binding ItemContent}" />
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
</StackPanel>
</Window>
MainWindowViewModel.cs
using Prism.Commands;
using Prism.Mvvm;
using System.Collections.ObjectModel;
using System.Windows.Controls;
using System.Windows.Input;
namespace WpfApp1
{
public class MainWindowViewModel : BindableBase
{
public MainWindowViewModel()
{
PreviewMouseDownCommand = new DelegateCommand<MouseEventArgs>(PreviewMouseDown);
PopulateItems();
}
public ICommand PreviewMouseDownCommand { get; }
private void PreviewMouseDown(MouseEventArgs e)
{
/// if SingleItemContent is clicked
/// e.Source is TextBox
/// if an ItemViewModel.ItemContent is clicked
/// e.Source is TabControl
}
private void PopulateItems()
{
ItemViewModels.Add(new ItemViewModel
{
ItemContent = new TextBox()
});
SingleItemContent = new TextBox();
}
public ObservableCollection<ItemViewModel> ItemViewModels { get; } = new ObservableCollection<ItemViewModel>();
public object SingleItemContent { get; set; }
}
public class ItemViewModel
{
public object ItemContent { get; set; }
}
}