代码之家  ›  专栏  ›  技术社区  ›  Eddie Deyo

能否向XAML中的数据绑定项控件添加额外的项?

  •  15
  • Eddie Deyo  · 技术社区  · 17 年前

    我有一个 ItemsControl 这是绑定到数据列表的数据 decimal 项目控制

    请注意,修改绑定到的列表,使其包含额外按钮(可能通过更改为 string s代替 十进制的 s) 不是一个好的选择,因为我想在最后一个按钮上附加一个命令。

    也不是一个好的选择,因为我的控件使用 UniformGrid

    这是我的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中再添加一个按钮。

    2 回复  |  直到 17 年前
        1
  •  23
  •   Robert Macnee    17 年前

    你可以使用 CompositeCollection 类。为此,它将多个集合或单个项组合为ItemsControl的ItemsSource。

    <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>
    
        2
  •  18
  •   Randolpho    15 年前

    不过,CompositeCollection的问题在于它不会继承父元素DataContext,因此您将无法写入:

    <CollectionContainer Collection={Binding ...}" />
    

    在它里面——或者更确切地说,它会让你,但你不会从中得到任何东西。因为最初的帖子要求-{Binding PossibleAmounts}-而不是绑定到StaticResource-这并不是一个真正的解决方案。

    http://blogs.msdn.com/nickkramer/archive/2006/08/18/705116.aspx

    http://www.vistax64.com/avalon/90-compositecollections-collectioncontainer-binding-issue.html

    http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/bd1a78c1-67ef-4d1e-9cbe-70bbe8eb8b44/

    推荐文章