WPF DataTomplate中Command无效

时间:2022-09-20 12:45:02

问题:在DataTomplate中添加一个Button,Button添加Command,但是Command生效。

原因:ItemTemplate的DataContext指代不明,需要改为父类的DataContext。

解决方法:使用RelativeSource关键字,手动指定DataComtext和Command。

<userControl:AutoHideTabControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Title}" Margin="5,0,0,0" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonDown">
<i:InvokeCommandAction
Command="{Binding Path=DataContext.TabItemClickCommand, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=userControl:AutoHideTabControl}}"
CommandParameter="{Binding RelativeSource={x:Static RelativeSource.TemplatedParent}}"></i:InvokeCommandAction>
</i:EventTrigger></i:Interaction.Triggers>
</TextBlock>
<!-- CommandParameter, 将父类作为参数传给后台命令 -->
<Button Content="Test" Command="{Binding Path=DataContext.(viewModels:CaseViewModel.TabItemClickCommand), RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=userControl:AutoHideTabControl}}"CommandParameter="{Binding RelativeSource={x:Static RelativeSource.TemplatedParent}}"></i:InvokeCommandAction>>
</StackPanel>
</DataTemplate>
</userControl:AutoHideTabControl.ItemTemplate>

对应后台代码:

// ViewModel构造函数
public Constructors()
{
TabItemClickCommand = new DelegateCommand<object>(TabItemClick);
} //命令声明
public DelegateCommand<object> TabItemClickCommand{get; private set;} //命令实现
public void TabItemClick(object obj)
{
var control = obj as ContentPresenter;
}

参考:WPF ListBoxItem DataTempldate command 执行问题