好吧,我已经抓了一段时间了。但未能找到我的问题的解决方案。我所拥有的是带有和ObservableCollection TabItems的MainViewModel。 MainViewModel设置为MainView(用户控件)的DataContext,后者又承载TabControl。 tabcontrol绑定到TabItems集合。 tabcontrol的内容将是ReportItems用户控件。
此设置主要用于报告SSRS的UI报告。第一个选项卡包含一个“报告”列表,其中显示了一些列表框,用户可以从中选择“报告参数”。选择参数后,用户不会单击按钮,该按钮会生成报告,并使用reporthost将选项卡添加到选项卡控件。
我试图从选项卡而不是主视图中选择报告的原因是要选择很多参数,如果我将列表框添加到MainView,则tabcontrol的剩余空间将会减少并且用户需要向下滚动才能查看报告。
我不确定我的设计是否存在缺陷,但我想找出一种方法来添加要添加到TabItem集合的新ReportItemViewModel。这意味着允许子选项卡通过将ReportItemViewModel对象发送到MainViewModel来添加兄弟,并添加到集合中。
我想过使用静态Collection来执行此操作,但这不会调用我的OnPropertyChange方法。此外,在MainViewModel中使用静态方法也无济于事,因为它无法将对象添加到集合中,因为集合不是静态的。
我不会在这里发布任何代码,因为我被困在如何开始自己。我查看了另一篇文章here,但无法弄清楚如何使用它。
很抱歉有很长的描述,只是想让问题清楚。
我愿意接受任何建议,如果我能得到更好的设计。我很绝望,任何帮助都会受到赞赏。
答案 0 :(得分:3)
向ICommand
添加MainViewModel
,向ObservableCollection
添加新项目,并使用RelativeSource
绑定从TabItem
中查找命令}
所以你的MainViewModel会有
ObservableCollection<IViewModel> TabItems
IViewModel SelectedTabItem
ICommand AddTabCommand
其中AddTabCommand
基本上是
void AddTab(IViewModel newItem)
{
TabItems.Add(newItem);
SelectedTabItem = newItem;
}
你的用户界面会看起来像这个
<DataTemplate DataType="{x:Type local:SelectReportViewModel}">
<Grid>
...
<!-- Use the CommandParameter property to pass specified ReportItemViewModel to open -->
<Button Command="{Binding DataContext.AddTabCommand,
RelativeSource={RelativeSource AncestorType={x:Type TabControl}}}" />
...
</Grid>
</DataTemplate>
<TabControl ItemsSource="{Binding TabItems}" />
另一种选择是使用某种事件系统,例如MVVM Light的Messenger
或Microsoft Prism的EventAggregator
来广播/订阅事件。
您的MainViewModel
会订阅AddTabEvents
,而您的SelectReportViewModel
会在应添加新标签时随时广播这些活动。如果您有兴趣,我会在我的博客文章中简要总结communication between ViewModels。