问题描述
我有一个 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.
请注意,修改我绑定到的列表以使其包含额外的按钮(可能通过更改为 string
s 而不是 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 添加额外的项目吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!