gpt4 book ai didi

c# - WPF, Prism : How to access non-static method in other module?

转载 作者:太空宇宙 更新时间:2023-11-03 15:03:11 25 4
gpt4 key购买 nike

据我了解,Prism 不会保留对创建的模块实例的引用。

当我无法访问当前正在使用的模块对象的实例时,如何从一个模块访问另一个模块中的非静态方法?

编辑:我通过从 View 中检索数据上下文并将其转换为使用的模型(我想要的方法所在的位置)来使其工作。不确定这是否是好的做法。

IRegionManager regionManager = ServiceLocator.Current.GetInstance<IRegionManager>();

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

Module.Views.View currentView= null;
foreach (Module.Views.View view in region.ActiveViews)
{
currentView = view;
}

var model = (Module.Model)currentView.DataContext;

mode.Method();

最佳答案

模块定义(也就是实现 IModule 的类)除了框架调用的 Initialize 方法外,不包含任何值得为任何人调用的方法。

如果你想在一个模块中实现一个方法并在另一个模块中使用它(或者在同一个模块中,也就是说,没关系),创建一个类并实现一个接口(interface)。

例子:

public interface IMyService
{
void MyMethod();
}

internal class MyImplementation : IMyService
{
#region IMyService
public void MyMethod()
{
// do something useful ModuleA's way
}
#endregion
}

internal class ModuleA : IModule
{
public ModuleA( IUnityContainer container )
{
_container = container;
}

#region IModule
public void Initialize()
{
_container.RegisterType<IMyService, MyImplementation>();
}
#endregion

#region private
private readonly IUnityContainer _container;
#endregion
}

internal class SomeClass
{
public SomeClass( IMyService myService )
{
_myService = myService;
}

public void SomeMethod()
{
// use ModuleA's method here:
_myService.MyMethod();
}

#region private
private readonly IMyService _myService;
#endregion
}

关于c# - WPF, Prism : How to access non-static method in other module?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45098192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com