【发布时间】:2016-12-29 17:05:47
【问题描述】:
我有以下 TabControl:
<TabControl ItemsSource="{Binding Tabs"}>
<TabControl.ContentTemplate>
<DataTemplate DataType="{x:Type vm:TabVM}">
<TextBox></TextBox>
<TextBox Text="{Binding SomeProperty}"></TextBox>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
意外的行为是第一个 TextBox 在所有 tabitems 之间共享 Text 属性,而第二个 TextBox 有效地绑定到 ViewModel 属性。
我的需要也是让第一个 TextBox 独立,即使没有绑定。
我能做什么?
** 更新 **
经过几次尝试,我决定使用 ikriv 的 TabContent.cs。 我发现的唯一问题是调用 TabControl.Items.Refresh()(即删除 tabItem 后)会导致内部缓存重置。
一个不雅但有效的解决方案可能是这样的:
public ContentManager(TabControl tabControl, Decorator border)
{
_tabControl = tabControl;
_border = border;
_tabControl.SelectionChanged += (sender, args) => { UpdateSelectedTab(); };
/* CUSTOM */
var view = CollectionViewSource.GetDefaultView(((TabControl)_tabControl).Items);
view.CollectionChanged += View_CollectionChanged;
}
/*
* This fix the internal cache content when calling items->Refresh() method
* */
private void View_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
/* Retrieve all tabitems cache and store to a temp list */
IList<ContentControl> cachedContents = new List<ContentControl>();
foreach (var item in _tabControl.Items)
{
var tabItem = _tabControl.ItemContainerGenerator.ContainerFromItem(item);
var cachedContent = TabContent.GetInternalCachedContent(tabItem);
cachedContents.Add(cachedContent);
}
/* rebuild the view */
_tabControl.Items.Refresh();
/* Retrieve all cached content and store to the tabitems */
int idx = 0;
foreach (var item in _tabControl.Items)
{
var tabItem = _tabControl.ItemContainerGenerator.ContainerFromItem(item);
TabContent.SetInternalCachedContent(tabItem, cachedContents[idx++]);
}
}
}
【问题讨论】:
-
试试
TabControl.ItemTemplate而不是ContentTemplate -
ItemTemplate 用于 TabItem 标头,而不是内容
-
如果您想设置项目模板,请使用
TabControl.ItemContainerStyle(<Style TargetType="TabItem">...) 并为TabItem的ContentTemplate属性赋予Style一个Setter。TabControl的ContentTemplate属性不是您想要的。这不是很好。 -
你可以试试这个,TabControlEx