开发者

How can we cast Frame.Content to a Page type in WPF

开发者 https://www.devze.com 2022-12-27 09:27 出处:网络
Basically; I need to invoke a method on my WPF page, from a WPF frame where I load the WPF Page. I get the loaded page using Frame.Content property, and cast it to my page type since Content property

Basically; I need to invoke a method on my WPF page, from a WPF frame where I load the WPF Page. I get the loaded page using Frame.Content property, and cast it to my page type since Content property returns Object type. The project builds successfully, however it throws InvalidCastException at runtime.

//This line throws InvalidCastException at runtime...
((PageA)TargetFrame.Content).methodA();

Here is the exception details:


[A]LoongNamespaceA.PageA cannot be cast to [B]LoongNamespaceA.PageA.
Type A originates from 'AssemblyA, Version=1.0.0.58, Culture=neutral, PublicKeyToken=null' in the context 'LoadFrom' at location 'C:\Users\abdullah.battal\AppData\Local\AssemblyA.dll'.
Type B originates from 'AssemblyA, Version=1.0.0.58, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location 'C:\loongPathToSourceProject\bin\AssemblyA.dll'.

notice the co开发者_运维百科ntext and location difference...

how can we solve this one?


Your class that is making the method call is expecting the assembly loaded into the default Context at 'C:\loongPathToSourceProject\bin\AssemblyA.dll'. The actual type being displayed was loaded from 'C:\Users\abdullah.battal\AppData\Local\AssemblyA.dll' into the LoadFrom context.

Since these types are from different assemblies on the disk, the type system recognizes them as different types and can not cast it to the type that you are doing the cast to (even if they have the same signature, .NET doesn't recognize them as the same as they came from a different context).

This article on MSDN describes that assemblies using LoadFrom have a few disadvantages, namely:

If an assembly is loaded with LoadFrom, and the probing path includes an assembly with the same identity but a different location, an InvalidCastException, MissingMethodException, or other unexpected behavior can occur.

You will probably want to rework how you are dynamically loading your assemblies.

0

精彩评论

暂无评论...
验证码 换一张
取 消