TabItem 内的 TabControl
我有绑定到 ViewModel 中可观察集合属性的选项卡。每个视图模型的DataTemplate
是一个包含内部选项卡控件的用户控件。当我在内部选项卡控件中切换选项卡,然后在外部选项卡控件中切换选项卡时,新选择的外部选项卡的内容显示选择的相同内部选项卡,而不是保留选择的选项卡。我尝试使用 x:Shared="False" 并确保视图模型上的 Equals
和 GetHashCode
方法正确实现。我还没有看到有人能够以 MVVM 之类的方式回答这个问题。
I have tabs bound to an observable collection property in a ViewModel. The DataTemplate
for each view model is a user control containing an inner tab control. When I switch tabs in the inner tab control and then switch tabs in the outer tab control, the content for the newly selected outer tab shows the same inner tab selected rather that preserving the tab was selected. I tried using x:Shared="False" and ensuring my Equals
and GetHashCode
methods on the view-models were implemented correctly. I haven't seen anyone out there able to answer this question in an MVVM-sort-of-way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
默认情况下,WPF 在切换选项卡时会回收
TabItem
。这意味着如果TabItem
的模板相同,它将重新使用已显示的项目并简单地更改其DataContext
如果您想维护控件状态,例如选定的项目,您需要将它们绑定到
DataContext
中的某些内容。因此,您的
TabItemViewModel
可能具有SelectedTabIndex
属性,该属性将绑定到内部 TabControl 的SelectedIndex
您会注意到 ListBoxes、TextBoxes 等内容具有相同的行为、复选框等。由于 TabItem 正在被回收,因此不会丢弃任何控件,因此它们的值不会被重置。唯一改变的是 DataContext。
编辑
还有一种替代方法是重写
TabControl
类来更改它处理 TabItem 的方式。我过去曾使用过此方法,因为如果 TabItem 的模板发生更改,它会丢弃整个 TabItem 并重新绘制它,这可能会导致性能下降。发布了一些代码此处 这会改变此行为,但该网站似乎已关闭。这是我使用的代码的副本,尽管我的版本已进行了一些更改。
By default, WPF recycles
TabItem
s when switching tabs. That means if theTabItem
's template is the same, it will re-use the already displayed item and simply change itsDataContext
If you want to maintain control states, such as selected items, you need to bind them to something in the
DataContext
.So your
TabItemViewModel
could have a property ofSelectedTabIndex
which would be bound to the inner TabControl'sSelectedIndex
You notice the same behavior with things like ListBoxes, TextBoxes, CheckBoxes, etc. Since the TabItem is being recycled, none of the controls are discarded so none of their values get reset. The only thing that changes is the DataContext.
Edit
There is an alternative of overwritting the
TabControl
class to change the way it handles TabItems. I have used this in the past because if an TabItem's Template changes, it discards the entire TabItem and re-draws it, which can cause a performance hit.There was some code posted here that would change this behavior, but the site seems down. Here's a copy of the code that I use, although the version I have has been altered a bit.