我声明了一个ViewModel
:
public class DefaultViewModel : WorkspaceViewModel
{
public DefaultViewModel()
{
this.DisplayName = "Welcome!";
}
}
我使用 CollectionViewSource
来设置我的活动“工作区”:
// this code comes from the MainWindowViewModel.cs
void SetActiveWorkspace(WorkspaceViewModel workspace)
{
Debug.Assert(this.Workspaces.Contains(workspace));
ICollectionView collectionView =
CollectionViewSource.GetDefaultView(this.Workspaces);
if (collectionView != null)
collectionView.MoveCurrentTo(workspace);
}
在 MainWindowViewModel.cs
的构造函数中,我设置了一个默认的“工作区”:
public MainWindowViewModel()
{
this.DisplayName = "Big File Reader";
var viewModel = new DefaultViewModel();
this.Workspaces.Add(viewModel);
this.SetActiveWorkspace(viewModel);
}
此时应该一切都正常。现在,我想要在新标签页中显示每个“工作区”,因此我标记了我的
TabControl
并进行了同步:<ContentControl Content="{Binding Path=Workspaces}">
<ContentControl.ContentTemplate>
<DataTemplate>
<TabControl IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding}"
Margin="4">
<TabControl.ItemTemplate>
<DataTemplate>
<DockPanel Width="120">
<Button Command="{Binding Path=CloseCommand}"
Content="X"
Cursor="Hand"
DockPanel.Dock="Right"
Focusable="False"
FontFamily="Courier"
FontSize="10"
FontWeight="Bold"
Margin="0,1,0,0"
Padding="4"
VerticalContentAlignment="Bottom"
Style="{DynamicResource
ResourceKey={
x:Static ToolBar.ButtonStyleKey}}"/>
<ContentPresenter
Content="{Binding Path=DisplayName}"
VerticalAlignment="Center"/>
</DockPanel>
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
</DataTemplate>
</ContentControl.ContentTemplate>
</ContentControl>
接下来,在外部资源文件中我定义了视图模型的默认视图:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:l="clr-namespace:BigFileReader"
xmlns:lv="clr-namespace:BigFileReader.Views">
<DataTemplate DataType="l:DefaultViewModel">
<lv:DefaultView/>
</DataTemplate>
</ResourceDictionary>
我将那个资源字典包含在我的主窗口中:
<Window.Resources>
<ResourceDictionary Source="MainWindowResources.xaml" />
</Window.Resources>
现在,对于每个
TabItem
,标题都显示得很好。按预期显示DisplayName
。
但是,TabItem
的ContentTemplate
没有使用默认视图,它只显示一个带有DefaultViewModel
的ToString()
的TextBlock
,而这当然是该类型的完整名称。
为什么不使用默认模板呢?