维护集合中的三个值

时间:2019-07-08 19:10:05

标签: c# wpf

我正在开发MVVM体系结构中的WPF应用程序。因此,我的项目中有许多ViewModels和视图。为了方便页面导航,创建了一个自定义导航服务类,并通过传递viewmodel或视图名称来获取其他名称。 下面的方法将在starup上调用。

private static void ConfigureNavigation()
{
    Uri test = new Uri("../Views/LoginView.xaml", UriKind.Relative); // I don't know how to pass to dictonary.
    NavigationService.Register<LoginViewModel, LoginView>();
    NavigationService.Register<MaintainerViewModel, MaintainerView>();
}

下面的代码是导航服务的注册方法

private static readonly ConcurrentDictionary<Type, Type> ViewModelMap = new ConcurrentDictionary<Type, Type>();
public static void Register<TViewModel, TView>() where TView : Page
{
   if (!ViewModelMap.TryAdd(typeof(TViewModel), typeof(TView)))
   {
      throw new InvalidOperationException($"ViewModel already registered '{typeof(TViewModel).FullName}'");
   }
}

要求1

我需要使用viewmodel将框架导航到指定的网址。

Frame.Navigate(GetView(viewModelType), UriKind.Relative);



public static Uri GetView(Type viewModel)
{
    if (ViewModelMap.TryGetValue(viewModel, out Type view))
    {
        return;  Here I need to return url, which is registered in the register method;
    }
    throw new InvalidOperationException($"View not registered for ViewModel '{viewModel.FullName}'");
}

通过传递视图模型,我需要获取视图和URL。

要求2 我需要使用视图名称来获取viewmodel。

public static Type GetViewModel(Type view)
{
    var type = ViewModelMap.Where(r => r.Value == view).Select(r => r.Key).FirstOrDefault();
    if (type == null)
    {
        throw new InvalidOperationException($"View not registered for ViewModel '{view.FullName}'");
    }
    return type;
}

通过视图,我需要获取viewmodel。

如何将Uri从ConfigureNavigation()传递到导航服务,并且不知道如何从字典中获取。唯一的问题是通过Uri。

任何帮助.. 如何将uri传递给Register()方法并获取GetView()方法

0 个答案:

没有答案