簡體   English   中英

如何綁定到其他項目/名稱空間中包含的集合?

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

我這樣做:

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

將組合框綁定到另一個項目/命名空間中的集合。 但是我不得不將ComboBox移到DataTemplate中。

現在我需要做這樣的事情:

<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">

因此,現在“ 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"

無關緊要的是,您可能希望綁定到Observable集合,以提高性能。 這里有更多WPF優化細節。

將IEnumerable綁定到ItemsControl會強制WPF創建包裝IList <(Of <(T>)>)對象,這意味着第二個對象的不必要開銷會影響您的性能。

好的,我找到了解決方法。 如果集合包含在另一個程序集中,則一定存在問題。

我在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}}"/>

這很好。
Thx Matt的幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM