是否可以通过regionManager.RequestNavigate注册View的名称,以便稍后从区域中删除它?

时间:2017-10-18 07:45:44

标签: c# wpf prism

在我的PRISM-App中,用户可以在TabView(Navigate("TestView"))中打开模块的视图。现在我想通过OnCloseTab("TestView")关闭此视图,但注册的视图没有名称。

public class MainWindowViewModel: BindableBase
{
...
    private void Navigate(string uri)
    {
        this.regionManager.RequestNavigate("TabRegion", uri);            
    } 

    private void OnCloseTab(string uri)
    {
        IRegion region = this.regionManager.Regions["TabRegion"];

        object view = region.GetView(uri);
        if (view != null)
        {
            region.Remove(view);
        }

    }
}

模块在我的引导程序中注册,如下所示:

protected override void ConfigureModuleCatalog()
{
    base.ConfigureModuleCatalog();

    ModuleCatalog moduleCatalog = (ModuleCatalog)this.ModuleCatalog;
    Type modulePType = typeof(Module.ProductionData.ProductionDataModule);                          
    moduleCatalog.AddModule(typeof(Module.ProductionData.ProductionDataModule));            
}

适用于:

IRegion region = regionManager.Regions["TabRegion"];

object view = region.GetView("TestView");
if (view == null)
{
    view = ServiceLocator.Current.GetInstance<Views.TestView>();
    region.Add(view, "TestView");
}

但是MainWindowViewModel不知道模块的视图。有什么方法可以删除视图,当它没有名称?谢谢你的任何建议

2 个答案:

答案 0 :(得分:1)

IRegionManager Add(object view, string viewName, bool createRegionManagerScope) 方法使用以下方法在内部将所选视图添加到区域:

RegionManager.Add(view, null, false);
使用以下参数调用

object view = region.Views.FirstOrDefault(v => v.GetType() == typeof(yourViewType));

因此没有名称与导航视图相关联。因此,无法使用视图名称/ uri检索视图对象。另一种方法是尝试匹配视图的.net类型:

didSelectItemAtIndexPath

如果这还不够,您仍然可以在视图对象上添加额外的属性,并尝试检索它们将视图转换为合适的类型。

答案 1 :(得分:0)

谢谢卢克。我找到了解决问题here

的解决方案

在我的MainWindowView.cs(XAML)中,我添加了以下内容:

<TabControl.ItemTemplate>
    <DataTemplate>
        <DockPanel Width="Auto">
            <Button Command="{Binding DataContext.CloseTabCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
    CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type TabItem}}}"
    Content="X"
    Cursor="Hand"
    DockPanel.Dock="Right"
    Focusable="False"
    FontFamily="Courier"
    FontWeight="Bold"
    Margin="4,0,0,0"
    FontSize="10"
    VerticalContentAlignment="Center"
    Width="15" Height="15" />

            <ContentPresenter Content="{Binding DataContext.DataContext.ViewTitle, RelativeSource={RelativeSource AncestorType={x:Type TabItem}}}" />
        </DockPanel>
    </DataTemplate>
</TabControl.ItemTemplate>

在我的MainWindowViewModel.cs我改变了我的CloseCommand:

public DelegateCommand<object> CloseTabCommand { get; set; }

public MainWindowViewModel(IRegionManager regionManager)
{
    this.regionManager = regionManager;

    CloseTabCommand = new DelegateCommand<object>(OnCloseTab);

}
private void OnCloseTab(object tabItem)
{
    var view = ((System.Windows.Controls.TabItem)tabItem).DataContext;
    this.regionManager.Regions["TabRegion"].Remove(view);
}