我有一个TabControl,其项目是ViewModel,是动态填充的。此外,还有一个UserControl链接到DataTemplate中的ViewModel。一切正常,显示效果很好。但是,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();
}