我声明了一个 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>
然后,在外部资源文件中,我为 View 模型定义了默认 View :
<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
没有选择默认 View ,它只是显示一个 TextBlock
DefaultViewModel
的ToString()
,当然是类型的全名。
为什么没有选择默认模板?
最佳答案
改变这个:
<DataTemplate DataType="l:DefaultViewModel">
<lv:DefaultView/>
</DataTemplate>
为此:
<DataTemplate DataType="{x:Type l:DefaultViewModel}">
<lv:DefaultView/>
</DataTemplate>
我遇到过一次。我为此苦苦挣扎了 1 小时,才发现这个简单的解决方案。试试吧。
关于c# - 为什么我的 View 模型的这个默认 DataTemplate 没有被拾取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18276291/