我正在用TabControl做一個WPF應用程序。在開始的時候我有必然的TabBase項目,其中TabBase是標籤視圖模型基類的ObservableCollection一個TabControl:TabControl ItemTemplate without ItemsSource
<TabControl
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Tabs}"
ItemTemplate="{StaticResource ClosableTabTemplate}"
...
public ObservableCollection<TabBase> Tabs { get; private set; }
...
public abstract class TabBase : ViewModelBase
...
public abstract class ViewModelBase : INotifyPropertyChanged
{
public virtual string DisplayName { get; protected set; }
...
<DataTemplate x:Key="ClosableTabTemplate">
<DockPanel Width="120">
<Button
Command="{Binding Path=CmdClose}"
Content="X"
/>
<ContentPresenter
Content="{Binding Path=DisplayName}">
</ContentPresenter>
</DockPanel>
</DataTemplate>
但我面臨着一個問題,當我切換標籤,它看起來像當前標籤是被每次創建,即使它之前已經打開。通過StackOverflow搜索我找到了解決方案here並參考here。我已經使用聲明式ItemsSource替換了代碼中動態創建的選項卡。選項卡切換性能問題已解決,但選項卡標題已經失去了與模板的鏈接,所以不是帶有標題和關閉按鈕的選項卡標題,而只是看到一個沒有任何內容的小選項卡標題。玩了一下製表符創建代碼,我能夠恢復製表大小和關閉按鈕,但沒有綁定 - 沒有標題和關閉按鈕不起作用(5行item.Header恢復原始標籤大小):
private void AddTabItem(TabBase view)
{
TabItem item = new TabItem();
item.DataContext = view;
item.Content = new ContentControl();
(item.Content as ContentControl).Focusable = false;
(item.Content as ContentControl).SetBinding(ContentControl.ContentProperty, new Binding());
item.Header = new ContentControl();
(item.Header as ContentControl).DataContext = view;
(item.Header as ContentControl).Focusable = false;
(item.Header as ContentControl).SetBinding(ContentControl.ContentProperty, new Binding());
item.HeaderTemplate = (DataTemplate)FindResource("ClosableTabTemplate");
tabControl.Items.Add(item);
}
問題是,我如何讓ItemTemplate在沒有ItemsSource綁定的情況下爲TabControl工作?
它的魔力,「第一路」解決了這個問題!謝謝! – sarh 2012-03-07 04:54:23