How do I bind to a collection contained in another project / namespace?

I did this:

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

      

to bind the combobox to a collection that is in a different project / namespace. But I had to move ComboBox

to DataTemplate.

Now I need to do something like this:

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

      

I do not want to list all my attempts, but none of them were successful.
Any better ideas?

+1


a source to share


3 answers


You need to map the .NET namespace to the XML namespace at the top of your XAML file:

<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 into the "Common.Component" namespace. You can now use the x: Static markup extension to access the "Instance" static property of your ModuleManager class:

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

      



See if this works for you.

Edit

One more thing, if your Common.Component namespace lives in a separate assembly, you need to tell the XAML that:

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

      

+3


a source


In the case of an unbound note, you can bind to the Observable collection instead of performance. Learn more about optimizing WPF here .



Binding an IEnumerable to an ItemsControl forces WPF to create an IList <(Of <(T>)>) wrapper object, which means your performance is affected by unnecessary overhead of the second object.

0


a source


Ok I found a workaround. There must be a problem if the collection is contained in another assembly.

I added a new class to the XAML assembly and bindings.

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 it works great.
thanks Matt for your help.

0


a source







All Articles