将ContextMenu命令绑定到父视图模型RelayCommand
本文关键字:视图 模型 RelayCommand ContextMenu 命令 绑定 | 更新日期: 2023-09-27 18:25:47
我有一个TvShowsViewModel
(1),它包含TvShowViewModel
s(2)的ObservableCollection
。TvShowViewModel
包含SeasonViewModel
s(3)的ObservableCollection
。
我有一个TreeView
,它具有TvShowsViewModel
(1)作为DataContext
。其中TreeView
的ItemSource
与TvShowViewModels
的ObservableCollection
结合(2)。
TreeView
指定HierarchicalDataTemplate
,其结合到SeasonViewModels
(3)的ObservableCollection
。
CCD_ 18包含一个CCD_。
现在,ContextMenu
包含一个Command
,我想将其绑定到TvShowsViewModel
(1)中的RelayCommand
。
我尝试了各种类型的RelativeSource
绑定,但都没有找到解决方案。我应该如何指定绑定?
TvShowsViewModel(1)
public class TvShowsViewModel : ViewModelBase
{
public RelayCommand ExcludeSeasonCommand { get; private set; }
public ObservableCollection<TvShowViewModel> TvShows { get; private set; }
public TvShowsViewModel(ITvShowsLibrary tvShowsLibrary)
{
TvShows = new ObservableCollection<TvShowViewModel>();
ExcludeSeasonCommand = new RelayCommand(ExcludeSeasonCommandOnExecute, ExcludeSeasonCommandOnCanExecute);
// Left out irrelevant code
}
}
TvShowViewModel(2)
public class TvShowViewModel : ViewModelBase, IFolderOnDisk
{
public ObservableCollection<SeasonViewModel> Seasons
{
get { return _seasons; }
}
// Left out irrelevant code
}
SeasonViewModel(3)
public class SeasonViewModel : ViewModelBase, IFolderOnDisk
{
// Left out irrelevant code
}
剥离的用户控件(TreeView)
<!-- Again, left out a lot of irrelevant parts -->
<TreeView ItemsSource="{Binding TvShows}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="tvShows:TvShowViewModel" ItemsSource="{Binding Seasons}">
<TextBlock Text="{Binding Name}" />
<HierarchicalDataTemplate.ItemTemplate>
<HierarchicalDataTemplate>
<TextBlock Text="{Binding Name}">
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem
Header="Exclude season"
<!-- This is where I need your help, how should I configure the binding? -->
Command="{Binding Path=DataContext.ExcludeSeasonCommand, RelativeSource={RelativeSource AncestorType=TreeView}}" />
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</HierarchicalDataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
绑定,我无法理解
最后,经过多次谷歌搜索,我找到了解决方案
<MenuItem
Header="Exclude season"
Command="{Binding DataContext.ExcludeSeasonCommand, Source={x:Reference _tvShowsTreeView}}" />
因为层次结构数据模板没有出现在可视化树中,所以没有"相对"源。。。
我希望这能帮助其他正在拔头发的人。。。