![](/img/trans.png)
[英]How should I bind a Combobox's ItemsSource to Content and Items
[英]How to bind Items to ItemsSource?
我想在單獨的面板中顯示myElement.ContextMenu圖標。 我正在嘗試這樣做:
<ItemsControl ItemsSource="{Binding ElementName=myElement, Path=ContextMenu.ItemsSource}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type MenuItem}">
<Image Source="{Binding Icon}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
但是它顯示了MenuItems而不是Images的集合。 如何在xxx.xaml.cs文件中沒有任何ViewModel和操作的情況下執行此操作。
您綁定到ContextMenu.ItemsSource
這是一個不同的屬性比ContextMenu.Items
僅當您將ItemsSource
設置為某種對象(例如對象集合)時,才會設置ItemsSource
,如果是這種情況,則您的ItemsControl
也將綁定到相同的對象集合。 除非將ItemsSource
使用的對象列表綁定到名為Icon
的屬性,否則您的代碼將無法工作。
如果嘗試綁定到ContextMenu.Items
,將獲得MenuItem
對象的集合,但是UI對象一次只能有一個父對象,因此MenuItems
只能存在於ContextMenu
或ItemsControl
,而不能同時存在於兩者中。
一種可能的方法是使用Converter進行綁定,該Converter將把對象放在ContextMenu
內部,並復制Icon
屬性,然后返回要顯示的圖像集合。 應該注意的是,只有在第一次打開ContextMenu
,該ContextMenu
才起作用,因為MenuItems
直到需要時才真正呈現。
<ItemsControl ItemsSource="{Binding ElementName=MyObjectWithContextMenu,
Converter={StaticResource MyConverter}}" />
其中MyConverter
需要傳遞給它的對象,獲取對象的ContextMenu
,通過每個循環MenuItem
中ContextMenu.Items
,存儲的副本Icon
屬性的List<T>
然后返回列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.