我的XAML中有下面的XAML
<ContextMenu x:Key="ExportContext">
<MenuItem Header="Export Journey"
Command="{Binding ExportJourney}"/>
<MenuItem Header="Export..."
ItemsSource="{Binding SelectedTrip.Clips}">
<MenuItem.ItemTemplate>
<DataTemplate>
<MenuItem Header="{Binding Name}"/>
</DataTemplate>
</MenuItem.ItemTemplate>
</MenuItem>
</ContextMenu>绑定到ExportJourney的第一个ExportJourney按预期工作,并从HomeViewModel运行ICommand。然而,SelectedTrip.Clips绑定似乎根本不起作用。
下面是HomeViewModel的摘录,它被赋值为窗口的DataContext
namespace ViewModel
{
class HomeViewModel: ObservableObject, IPageViewModel
{
private ICommand _exportJourney;
private ObservableCollection<Journey> _journeyList = new ObservableCollection<Journey>();
private Journey _selectedTrip;
public IEnumerable<Journey> JourneyList
{
get { return _journeyList; }
}
public Journey SelectedTrip
{
get { return _selectedTrip; }
set
{
if (_selectedTrip != value)
{
_selectedTrip = value;
_journeyList.Where(c => c.Selected == true).ToList().ForEach(a => a.Selected = false);
_journeyList.Where(c => c.StartTime == value.StartTime).ToList().ForEach(a => a.Selected = true);
OnPropertyChanged("SelectedTrip");
}
}
}
public ICommand ExportJourney
{
get
{
if (_exportJourney == null)
{
_exportJourney = new RelayCommand(
p => ExtractJourney(),
p => SelectedTrip != null);
}
return _exportJourney;
}
}
}
}Journey类包含一个属性Clips,它是一个List<Clip>。然后,Clip类包含要显示的Name的string属性。
JourneyList显示在DataGrid中,并选择一行,将Journey设置为SelectedTrip
我不明白为什么绑定到ExportJourney ICommand是完美的,但是在导出项下没有出现任何东西.头球。我唯一能想到的是,在加载时SelectedJourney是空的?
如果出于测试目的,我绑定到JourneyList而不是SelectedTrip.Clips绑定工作,那么我会得到一个子菜单(尽管没有名字,但位置在那里!)
不太确定该做什么来调试这个?任何关于调试绑定的建议,或者关于我做错了什么的建议,都是非常感谢的!
发布于 2017-04-28 10:50:32
在不到10分钟的时间内回答了我自己的问题,但我花了一个星期的时间在谷歌上发布了这个问题。有时候我讨厌这个世界的运作方式!
回答: ItemsSource在ContextMenu上不能是list类型的。
我调整了我的Journey类,使公共Clip属性成为IEnumerable<Clip> (私有Clip属性变成ObservableCollection<Clip>),而不是List<Clip>。
https://stackoverflow.com/questions/43678100
复制相似问题