简体   繁体   English

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

[英]How to bind to a collection contained in an other project/namespace?

i did this: 我这样做:

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

to bind the combobox to a collection, which is located in an other project/namespace. 将组合框绑定到另一个项目/命名空间中的集合。 But i had to move the ComboBox into a DataTemplate. 但是我不得不将ComboBox移到DataTemplate中。

Now i need to do something like that: 现在我需要做这样的事情:

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

I don't want to list all of my tries, but none were successful. 我不想列出所有尝试,但都没有成功。
Any better Ideas? 还有更好的主意吗?

You need to map the .NET namespace to an XML namespace at the top of your XAML file: 您需要将.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">

So now "q" is mapped to the "Common.Component" namespace. 因此,现在“ q”被映射到“ Common.Component”名称空间。 Now you can use the x:Static markup extension to access the static "Instance" property of your ModuleManager class: 现在,您可以使用x:Static标记扩展名来访问ModuleManager类的静态“实例”属性:

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

See if that works for you. 看看是否适合您。

Edit 编辑

One more thing: If your "Common.Component" namespace lives in a separate assembly, you need to tell the XAML that: 还有一件事:如果您的“ Common.Component”命名空间位于单独的程序集中,则需要告诉XAML:

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

On an unrelated note you might want to bind to an Observable collection instead for performance. 无关紧要的是,您可能希望绑定到Observable集合,以提高性能。 More WPF optimization details here . 这里有更多WPF优化细节。

Binding IEnumerable to an ItemsControl forces WPF to create a wrapper IList<(Of <(T>)>) object, which means your performance is impacted by the unnecessary overhead of a second object. 将IEnumerable绑定到ItemsControl会强制WPF创建包装IList <(Of <(T>)>)对象,这意味着第二个对象的不必要开销会影响您的性能。

Ok, i found a workaround. 好的,我找到了解决方法。 There must be a Problem if the collection is contained in an other assembly. 如果集合包含在另一个程序集中,则一定存在问题。

I added a new class to the assembly of the XAML and the Binding. 我在XAML和Binding的程序集中添加了一个新类。

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

Then i changed the binding to 然后我将绑定更改为

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

And this works fine. 这很好。
Thx Matt for your help. Thx Matt的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM