WPF DataTemplate - 将新项目添加到集合时触发事件?
当新项目添加到 Flights
集合中时,新的 TabItem
也会添加到 TabControl
中。添加新选项卡时,我需要调用图表控件上的方法。问题是我无法找出要处理的正确事件。
我的 XAML 如下所示:
<TabControl Name="chartControl" ItemsSource="{Binding Flights}">
<TabControl.ItemContainerStyle>
<Style TargetType="TabItem">
<Setter Property="Header" Value="{Binding Name}" />
</Style>
</TabControl.ItemContainerStyle>
<TabControl.ContentTemplate>
<DataTemplate>
<WindowsFormHost Name="winHost">
<legacy:Chart></legacy:Chart>
</WindowsFormHost>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
- 我尝试处理
TabControl
上的Loaded
, 但是呃只触发了一次。 - 我尝试了
DataTemplate
RoatedEvent
上的触发器
FrameWorkElement.Loaded
但我很确定这不适合我的情况 - 我尝试了 EventSetter 但那 不太按照我想要的方式工作 或者
我尝试了一些其他的事情,但我不太记得它们了。
任何建议将不胜感激!
When a new item is added to the Flights
collection a new TabItem
is added to the TabControl
. When a new tab is added, I need to call a method on the Chart control. The problem is I can't figure out the right event to handle.
My XAML looks something like the following:
<TabControl Name="chartControl" ItemsSource="{Binding Flights}">
<TabControl.ItemContainerStyle>
<Style TargetType="TabItem">
<Setter Property="Header" Value="{Binding Name}" />
</Style>
</TabControl.ItemContainerStyle>
<TabControl.ContentTemplate>
<DataTemplate>
<WindowsFormHost Name="winHost">
<legacy:Chart></legacy:Chart>
</WindowsFormHost>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
- I tried handling the
Loaded
on theTabControl
,
but duh that's only fired once. - I attempted a
DataTemplate
Trigger
on theRoutedEvent
FrameWorkElement.Loaded
but I'm pretty sure that's not meant for my situation - I tried an EventSetter but that
didn't quite work the way I want
either
I attempted a few other things, but I don't quite remember them all.
Any suggestions would be greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我正确读取您的 XAML,您是否正在为 TabControl 创建单个图表控件并在 TabItem 更改时更改其数据?如果是这样,您应该能够使用
SelectionChanged
事件。您最好将 Chart 控件放在 ItemTemplate 中,这样当用户切换选项卡或添加新选项卡时,它会自动加载选定的
Flights
数据。If I'm reading your XAML correctly, you are creating a single Chart control for the TabControl and changing its data when the TabItem changes? If so, you should be able to use the
SelectionChanged
event.You might be better off putting your Chart control in the ItemTemplate so it automatically loads the selected
Flights
data when the user switches tabs or adds a new one.您的
Flights
集合的类型应为 ObservableCollection<>< /a>. xaml 中的 ItemsSource 绑定将订阅其 CollectionChanged 事件并添加/删除选项卡。至于调用Chart上的方法,WindowsFormHost有Loaded事件吗?因为将为创建的每个选项卡创建一个新选项卡。Your
Flights
collection should be of type ObservableCollection<>. The ItemsSource binding in xaml will subscribe to its CollectionChanged event and add/remove tabs. As for calling the method on the Chart, does the WindowsFormHost have a Loaded event? Because a new one will be created for each tab that's created.