可以在XAML中的数据绑定的ItemsControl中添加一个额外的项目吗? [英] Can you add an extra item to a data bound ItemsControl in XAML?
问题描述
我有一个 ItemsControl
,它是绑定到 decimal
的列表的数据。我需要为 ItemsControl
添加一个额外的控件(一个手动指定号码的选项)。有没有办法在XAML这样做?我知道我可以在后面的代码中手动添加项目,但是我想要更好地了解WPF,并希望看到是否有一种声明性的方式来实现。
I have an ItemsControl
that is data bound to a list of decimal
s. I need to add one extra control to the ItemsControl
(an option to specify the number manually). Is there a way to do this in XAML? I know I can manually add the item in the code behind, but I'm trying to understand WPF a little better and want to see if there is a declarative way to do it.
请注意,修改我绑定的列表,以便它包含额外的按钮(可能通过更改为字符串
而不是 decimal
s)不是一个很好的选择,因为我想附加一个命令到最后一个按钮。
Note that modifying the list I'm binding to so that it includes the extra button (possibly by changing to a list of string
s instead of decimal
s) isn't a good alternative because I want to attach a command to that last button.
另外,添加一个额外的按钮之后 ItemsControl
也不是一个很好的选择,因为我的控件使用一个 UniformGrid
,我想要我的额外控制相同的网格。
Also, adding an extra button after the ItemsControl
isn't a good option either, because my control uses a UniformGrid
and I want my extra control in that same grid.
这是我的XAML:
<ItemsControl ItemsSource="{Binding PossibleAmounts}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Name="ButtonsGrid">
</UniformGrid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button>
<TextBlock Text="{Binding StringFormat='\{0:C\}'}"/>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
基本上,我想在UniformGrid中再一个按钮。
Basically, I want one more button in the UniformGrid.
推荐答案
您可以使用 CompositeCollection 类,为此目的,它将多个集合或单个项目作为ItemsControl的ItemsSource组合。
You can use the CompositeCollection class for this purpose, it combines multiple collections or individual items as the ItemsSource for an ItemsControl.
有一个很好的例子MSDN文章或另一个:
There's a good example in the MSDN article, or here's another one:
<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid.Resources>
<x:Array x:Key="intData" Type="{x:Type sys:Int32}">
<sys:Int32>1</sys:Int32>
<sys:Int32>2</sys:Int32>
<sys:Int32>3</sys:Int32>
</x:Array>
<x:Array x:Key="stringData" Type="{x:Type sys:String}">
<sys:String>Do</sys:String>
<sys:String>Re</sys:String>
<sys:String>Mi</sys:String>
</x:Array>
</Grid.Resources>
<ListBox>
<ListBox.ItemsSource>
<CompositeCollection>
<CollectionContainer Collection="{StaticResource intData}"/>
<CollectionContainer Collection="{StaticResource stringData}"/>
<ListBoxItem>One more item!</ListBoxItem>
<ListBoxItem>Two more items!</ListBoxItem>
</CompositeCollection>
</ListBox.ItemsSource>
</ListBox>
</Grid>
这篇关于可以在XAML中的数据绑定的ItemsControl中添加一个额外的项目吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!