如何使用类似外接程序的架构来扩展 WPF 应用程序?

发布于 2024-09-01 07:19:55 字数 244 浏览 2 评论 0原文

假设我有一个 WPF 应用程序,它显示一个 ListBox,其中包含一个 ArrayList(填充有任意类型的对象)作为源,并且该应用程序托管在程序集“A”中。默认情况下,ListBox 将显示自定义对象“ToString”方法的返回值。如果找到该对象类型的数据模板,ListBox 将使用它进行渲染。 想象一下,有另一个程序集“B”引用“A”,并试图通过为某些类型提供自定义数据模板来扩展它,以便在该列表框中使用。有什么方法可以在“A”不知道 B 的情况下做到这一点吗?

Lets say I have a WPF application that shows a ListBox with an ArrayList -populated with objects of arbitrary types- as a source, and this application is hosted in an assembly 'A'. By default the ListBox will display the custom object 'ToString' method return value. If a data template for that object type is found, the ListBox will use it for rendering.
Imagine that theres another assembly 'B' that references of 'A' and seeks to extend it by providing custom data templates for certain types, to be used in that ListBox. Is there some way to do that without 'A'being aware of B?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

2024-09-08 07:20:00

是的,这是 WPF 的一个非常常见的用法。

在程序集 B 中:

  1. 创建一个 Themes 文件夹,其中包含一个名为 Generic.xaml 的文件,其中包含一个空的 标记
  2. 标记内,添加 DataTemplates 和 ControlTemplates对于 B 中的类型
  3. 在 AssemblyInfo.cs 文件中,添加以下行:

    [程序集:ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]

现在在您的程序集 A:

  1. 创建一个 UI 来浏览到程序集 B(或以其他方式选择 .dll 文件)
  2. 当用户选择要使用的程序集 B 时,使用 var assembly = Assembly.LoadFile(path) 来加载它
  3. 使用 Activator.CreateInstance(Assembly.GetType(typeName)) 在程序集 B 中创建一个只知道其名称的对象
  4. 将此对象添加到您的 UI,或使用在其上定义的接口创建其他对象(接口其本身是在程序集 A 中定义的,并将其添加到您的 UI 中。

程序集 B 中定义的模板将用于呈现程序集 B 中的控件和数据,即使程序集 A 对程序集 B 一无所知。

Yes, this is a very common usage of WPF.

In your assembly B:

  1. Create a Themes folder containing a file named Generic.xaml containing an empty <ResourceDictionary> tag
  2. Inside the <ResourceDictionary> tag, add DataTemplates and ControlTemplates for the types in B
  3. In your AssemblyInfo.cs file, add the following line:

    [assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]

Now in your assembly A:

  1. Create a UI to browse to assembly B (or otherwise select the .dll file)
  2. When the user selects an assembly B to use, use var assembly = Assembly.LoadFile(path) to load it
  3. Use Activator.CreateInstance(assembly.GetType(typeName)) to create an object in assembly B knowing only its name
  4. Add this object to your UI, or create other objects using an interface defined on it (the interface itself is defined in assembly A) and add the to your UI

The templates defined in assembly B will be used to present the controls and data in assembly B, even though assembly A knows nothing of assembly B.

小糖芽 2024-09-08 07:19:58

请查看复合应用程序指南。它应该适合你。

Take a look on Composite Application Guidance. It should work for you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文