我有一个 TabControl,它的项目是动态填充的 ViewModel。此外,DataTemplate 中还有一个链接到 ViewModel 的 UserControl。一切正常,显示正常。但是,无论有多少个选项卡,SecurityRoleControl 的构造函数都只会创建一次。我需要在构造 UserControl 期间添加处理逻辑,但问题是它只在应用程序中调用一次。有人可以告诉我这种行为的原因以及可能的解决方法吗?高度赞赏。提前致谢。
// MainWindow.XAML code
<TabControl
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding ElementName=AdminMainWindow, Path=Workspaces}"
ItemTemplate="{StaticResource ClosableTabItemTemplate}"
Margin="4">
</TabControl>
// Data Template in Dictionary
<DataTemplate x:Key="ClosableTabItemTemplate">
<DockPanel Width="120">
<Button
Command="{Binding Path=CloseCommand}"
Content="X"
Cursor="Hand"
DockPanel.Dock="Right"
Focusable="False"
FontFamily="Courier"
FontSize="9"
FontWeight="Bold"
Margin="0,1,0,0"
Padding="0"
VerticalContentAlignment="Bottom"
Width="16" Height="16" />
<ContentPresenter
Content="{Binding Path=DisplayName}"
VerticalAlignment="Center" />
</DockPanel>
</DataTemplate>
// Binding of ViewModel to UserControl
<DataTemplate DataType="{x:Type vm:SecurityRoleViewModel}">
<uc:SecurityRoleControl />
</DataTemplate>
// Code to add a ViewModel to Workspace
SecurityRoleViewModel workspace = new SecurityRoleViewModel("Security Role Search");
workspace.MRN = viewModel.MRN;
workspaces.Add(workspace);
ICollectionView collectionView = CollectionViewSource.GetDefaultView(workspaces);
if (collectionView != null) {
collectionView.MoveCurrentTo(workspace);
}
// Workspaces
public ObservableCollection<WorkspaceViewModel> Workspaces { get { return workspaces; } }
// Constructor of SecurityRoleControl, which is called only once
public SecurityRoleControl() {
InitializeComponent();
}