I have a TabControl where I load multiple Views using the regionManager.RequestNavigate method. All the Views have the same type.
The Header of each TabItem has a button that I would like to use to remove the view when it is pressed, with the following code:
regionManager.Regions["MainContentRegion"].Remove(view)
My problem is that I don't know how can I get the instance of the view containing the button that was pressed in the viewmodel. This is not always the Active view of the TabControl, but can be also a non-active view since the button is in the Header of each TabItem.
Also, I could not find a way to set the name of the view in the RequestNavigate method...
Any help is very appreciated!
I've found a solution to my issue. What I have done is passing the view itself as a parameter of the Button Command. I defined the DataTemplate of the TabItem Header inside a style that is in the MainWindow.xaml The Header consist of a ContentControl and a Button. Following the code that Bind the Command of the button to an event defined in the ViewModel of the View that will be loaded into the TabItem. The Content of the TabItem is the actual view that is passed as a CommandParameter:
<Button Command="{Binding DataContext.DataContext.CloseViewCommand, RelativeSource={RelativeSource AncestorType={x:Type TabItem}}}" CommandParameter="{Binding Content, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TabItem}}}">
The code that manage the button click is defined inside the ViewModel of the View, that is defined inside a Module dynamically loaded. In the ViewModel I can simply remove the view from the region, using the following code:
public DelegateCommand<object> CloseViewCommand
{
get
{
if (_closeViewCommand == null)
_closeViewCommand = new DelegateCommand<object>(CloseView);
return _closeViewCommand;
}
}
private void CloseView (object view)
{
if (_regionManager.Regions[MainWindowRegions.MainContentRegion].Views.Contains(view))
_regionManager.Regions[MainWindowRegions.MainContentRegion].Remove(view);
}