【问题标题】:How to bind to a collection contained in an other project/namespace?如何绑定到其他项目/命名空间中包含的集合?
【发布时间】:2009-05-25 21:34:39
【问题描述】:

我这样做了:

this.combobox.ItemsSource = Common.Component.ModuleManager.Instance.Modules;

将组合框绑定到位于其他项目/命名空间中的集合。但我不得不将 ComboBox 移到 DataTemplate 中。

现在我需要做这样的事情:

<ComboBox ItemsSource="{Binding Common.Component.ModuleManager.Instance.Modules}"/>

我不想列出我的所有尝试,但没有一个成功。
有更好的想法吗?

【问题讨论】:

  • 我刚刚使用您的确切代码编译并运行了一个程序 - 工作正常。我唯一没有做的是将班级放入不同的程序集中。这一定比表面上看到的要多。
  • XamlParseException 是否提供了有关它具体抱怨什么的任何详细信息?如果从 ComboBox 中删除 ItemsSource 属性,它会消失吗?
  • 是的,如果我删除 ItemsSource 属性,也不例外。并且没有特别抱怨我可以看到的堆栈跟踪。但我上传了它,也许你会发现我错过的东西。 informatik.uni-rostock.de/~mb004/XamlParseException.txt(对不起里面的德国人)
  • 你让我很难过,这是肯定的。该错误发生在运行时?编译好了吗?
  • 是的......加载 ComboBox。如果 ContentenPresenter 显示一个 ArtifactViewModel。

标签: c# wpf data-binding xaml


【解决方案1】:

您需要将 .NET 命名空间映射到 XAML 文件顶部的 XML 命名空间:

<Window 
    x:Class="WindowsApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:q="clr-namespace:Common.Component">

所以现在“q”被映射到“Common.Component”命名空间。现在您可以使用 x:Static 标记扩展来访问 ModuleManager 类的静态“实例”属性:

<ComboBox
    ItemsSource="{Binding Modules,Source={x:Static q:ModuleManager.Instance}}" />

看看这是否适合你。

编辑

还有一件事:如果您的“Common.Component”命名空间位于单独的程序集中,您需要告诉 XAML:

xmlns:q="clr-namespace:Common.Component;assembly=CommonAssemblyFilename"

【讨论】:

  • 这在加载 ComboBox 时以 XamlParseException 结束
  • 有吗?这很奇怪。从未见过VS这样做。好的,你能用“ModuleManager”类的更多细节更新你的问题吗?我是否正确地认为那是类而 Instance 是静态属性? '因为 XAML 应该可以工作。
  • 出于兴趣,尝试“Binding Path=Modules”,而不仅仅是“Binding Modules”(其余部分保持不变)。
【解决方案2】:

在不相关的注释中,您可能希望绑定到 Observable 集合以提高性能。更多WPF优化细节here.

将 IEnumerable 绑定到 ItemsControl 会强制 WPF 创建包装器 IList)>) 对象,这意味着您的性能会受到第二个对象的不必要开销的影响。

【讨论】:

  • 我不需要 ObservableCollection。项目启动后集合永远不会改变。
【解决方案3】:

好的,我找到了解决方法。如果集合包含在其他程序集中,则一定有问题。

我在 XAML 和 Binding 的程序集中添加了一个新类。

public static class ResourceHelper
{
    public static IEnumerable<Common.Component.Module> Modules = Common.Component.ModuleManager.Instance.Modules;
}

然后我将绑定更改为

<ComboBox ItemsSource="{Binding Path=.,Source={x:Static e:ResourceHelper.Modules}}"/>

这很好用。
感谢 Matt 的帮助。

【讨论】:

  • 我还是不明白。我以这种方式在其他程序集中使用了集合。不过,我很高兴你能成功!
  • 我也不明白。我更改了项目的某些部分,现在我再次获得了 Excetion,但不是在每台 PC 上。看起来这个问题来自 wpf 的深处。
猜你喜欢
  • 2021-05-17
  • 2013-02-16
  • 1970-01-01
  • 2011-10-25
  • 2019-07-12
  • 1970-01-01
  • 2014-06-24
  • 1970-01-01
  • 2023-04-06
相关资源
最近更新 更多