将ContextMenu命令绑定到父视图模型RelayCommand

时间:2014-10-06 18:43:07

标签: c# wpf data-binding treeview parent

我有一个TvShowsViewModel(1),其中包含ObservableCollectionTvShowViewModel s(2)。 TvShowViewModel包含ObservableCollection SeasonViewModel s(3)。

我有一个TreeViewTvShowsViewModel(1)为DataContextItemSource的{​​{1}}绑定到TreeView的{​​{1}}(2)。

ObservableCollection指定TvShowViewModels,其绑定TreeView HierarchicalDataTemplate。{/ p>

ObservableCollection包含SeasonViewModels

现在,HierarchicalDataTemplate包含ContextMenu,我想绑定到ContextMenu(1)中的Command

我尝试了各种RelayCommand绑定,但没有任何方法可以解决问题。我该如何指定绑定?

TvShowsViewModel(1)

TvShowsViewModel

TvShowViewModel(2)

RelativeSource

SeasonViewModel(3)

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
    }
}

剥离的用户控件(TreeView)

public class TvShowViewModel : ViewModelBase, IFolderOnDisk
{
    public ObservableCollection<SeasonViewModel> Seasons
    {
        get { return _seasons; }
    }

    // Left out irrelevant code
}

绑定,我无法弄清楚

1 个答案:

答案 0 :(得分:6)

最后,经过许多谷歌搜索,我遇到了解决方案

<MenuItem
    Header="Exclude season"
    Command="{Binding DataContext.ExcludeSeasonCommand, Source={x:Reference _tvShowsTreeView}}" />

因为HierarchicalDataTemplate没有出现在可视化树中,所以没有“相对”源...

我希望这可以帮助那些正在拉扯他/她头发的人......