Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何绑定到包含在其他项目/命名空间中的集合?_C#_Wpf_Data Binding_Xaml - Fatal编程技术网

C# 如何绑定到包含在其他项目/命名空间中的集合?

C# 如何绑定到包含在其他项目/命名空间中的集合?,c#,wpf,data-binding,xaml,C#,Wpf,Data Binding,Xaml,我这样做: this.combobox.ItemsSource = Common.Component.ModuleManager.Instance.Modules; 将组合框绑定到位于其他项目/命名空间中的集合。但是我必须将组合框移动到数据模板中 现在我需要这样做: <ComboBox ItemsSource="{Binding Common.Component.ModuleManager.Instance.Modules}"/> 我不想列出我所有的尝试,但没有一次成功。 有

我这样做:

this.combobox.ItemsSource = Common.Component.ModuleManager.Instance.Modules;
将组合框绑定到位于其他项目/命名空间中的集合。但是我必须将
组合框
移动到数据模板中

现在我需要这样做:

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

我不想列出我所有的尝试,但没有一次成功。

有更好的主意吗?

您需要将.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">

在一个不相关的注释中,您可能希望绑定到一个可观察的集合,而不是性能。更多WPF优化细节

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


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

我向XAML和绑定的程序集添加了一个新类

public static class ResourceHelper
{
    public static IEnumerable<Common.Component.Module> Modules = Common.Component.ModuleManager.Instance.Modules;
}
公共静态类ResourceHelper
{
公共静态IEnumerable模块=Common.Component.ModuleManager.Instance.Modules;
}
然后我将绑定更改为

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

这很好用。

感谢您的帮助。

在加载ComboBoxIt时,这将以XamlParseException结束?那是。。。奇怪的从未见过VS这样做。好的,你能用更多关于“ModuleManager”类的细节更新你的问题吗?我是否认为类和实例是静态属性?”因为XAML应该可以工作。出于兴趣,请尝试“Binding Path=Modules”而不仅仅是“Binding Modules”(其余部分保持不变)。我刚刚编译并运行了一个程序,使用了您的精确代码,工作得很好。我唯一没有做的就是把这个类放到另一个程序集中。这其中肯定有很多不尽如人意的地方。XamlParseException是否提供了关于它具体抱怨什么的详细信息?如果从组合框中删除ItemsSource属性,它会消失吗?是的,如果我删除ItemsSource属性,则没有例外。我所能看到的stacktrace没有特别的抱怨。但我上传了,也许你会发现我遗漏了什么。(对里面的德国人感到抱歉)你肯定把我难住了。这个错误发生在运行时?它编译好了吗?是的。。。在组合框加载时。如果ContentPresenter显示一个ArtifactViewModel,我不需要ObservableCollection。项目启动后,集合从未更改。我仍然不明白。我曾以这种方式在其他程序集中使用过集合。不过,我很高兴你让它工作了!我也不明白。我改变了项目的一些部分,现在我又得到了这个额外的东西,但不是在每台电脑上。看起来这个问题来自wpf的深层次。
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}}"/>