如何在PRISM 4中导航到新视图时改进传递对象

Dar*_*Zon 3 c# navigation wpf prism module

我正在使用Prism和IoC.问题是通过导航传递对象(如集合).我正在看这篇文章:如何在导航到PRISM 4中的新视图时传递对象

这就是解决方案

我提取对象的哈希码并将其保存在一个中Dictionary,哈希码作为键,对象作为对的值.

然后,我将哈希码附加到UriQuery.

之后,我只需要在目标视图上获取来自Uri的哈希码,并使用它来从中请求原始对象Dictionary.

一些示例代码:

参数存储库类:

public class Parameters
{
    private static Dictionary<int, object> paramList =
        new Dictionary<int, object>();

    public static void save(int hash, object value)
    {
        if (!paramList.ContainsKey(hash))
            paramList.Add(hash, value);
    }

    public static object request(int hash)
    {
        return ((KeyValuePair<int, object>)paramList.
                    Where(x => x.Key == hash).FirstOrDefault()).Value;
    }
}
Run Code Online (Sandbox Code Playgroud)

来电者代码:

UriQuery q = null;
Customer customer = new Customer();
q = new UriQuery();
Parameters.save(customer.GetHashCode(), customer);
q.Add("hash", customer.GetHashCode().ToString());

Uri viewUri = new Uri("MyView" + q.ToString(), UriKind.Relative);
regionManager.RequestNavigate(region, viewUri);
Run Code Online (Sandbox Code Playgroud)

目标视图代码:

public partial class MyView : UserControl, INavigationAware
{
// some hidden code

    public void OnNavigatedTo(NavigationContext navigationContext)
    {
        int hash = int.Parse(navigationContext.Parameters["hash"]);
        Customer cust = (Customer)Parameters.request(hash);
    }
}
Run Code Online (Sandbox Code Playgroud)

而已.

我不确定这个解决方案是否最适合传递对象.我想这可能是一项服务.这是一个很好的方法,或者有更好的方法吗?

whi*_*hac 6

我发布了一个更简单的方法 在此提及以供参考 -

我将使用OnNavigatedTo和OnNavigatedFrom方法使用NavigationContext传递对象.

首先从INavigationAware接口派生viewmodel -

 public class MyViewModel : INavigationAware
 { ...
Run Code Online (Sandbox Code Playgroud)

然后,您可以实现OnNavigatedFrom并将要传递的对象设置为导航上下文,如下所示 -

void INavigationAware.OnNavigatedFrom(NavigationContext navigationContext)
{
     SharedData data = new SharedData();
     ...
     navigationContext.NavigationService.Region.Context = data;
}
Run Code Online (Sandbox Code Playgroud)

当您想要接收数据时,在第二个视图模型中添加以下代码 -

void INavigationAware.OnNavigatedTo(NavigationContext navigationContext)
{
    if (navigationContext.NavigationService.Region.Context != null)
    {
        if (navigationContext.NavigationService.Region.Context is SharedData)
        {
             SharedData data = (SharedData)navigationContext.NavigationService.Region.Context;
              ...
        }
    }
}
Run Code Online (Sandbox Code Playgroud)