绑定ItemsSource时如何将按钮添加到wpf列表框

我现在有这个:


    <ListBox ItemsSource="{Binding Items}">

        <ListBox.ItemsPanel>

            <ItemsPanelTemplate>

                <UniformGrid/> 

            </ItemsPanelTemplate>

        </ListBox.ItemsPanel>

    </ListBox>

但我需要这样的东西

http://img.mukewang.com/6173c8d80001c1ef08830358.jpg

不幸的是,当我以编程方式添加按钮时

ListBox.Items.Add(button);

它抛出一个错误 -

使用 ItemsSource 时操作无效


红糖糍粑
浏览 181回答 2
2回答

哆啦的时光机

CompositeCollection正是您所需要的。这是小XAML样本:<Window ...>&nbsp; &nbsp; <!-- You should define your ItemsSource in resources-->&nbsp; &nbsp; <Window.Resources>&nbsp; &nbsp; &nbsp; &nbsp; <CollectionViewSource x:Key="Names" Source="{Binding Names}" />&nbsp; &nbsp; </Window.Resources>&nbsp; &nbsp; <Grid>&nbsp; &nbsp; &nbsp; &nbsp; <ListBox>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ListBox.ItemsSource>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <CompositeCollection>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <CollectionContainer Collection="{Binding Source={StaticResource Names}}" />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ListBoxItem Foreground="Red">Add new...</ListBoxItem>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </CompositeCollection>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </ListBox.ItemsSource>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <!-- Here you can customize everything you want -->&nbsp; &nbsp; &nbsp; &nbsp; </ListBox>&nbsp; &nbsp; </Grid></Window>

小唯快跑啊

像这样使用,var myButton = new Button(){&nbsp; &nbsp;Height = 25,&nbsp; &nbsp;Width = 80&nbsp; &nbsp;Content = "+",&nbsp; &nbsp;Background = Brushes.Gray}UniformGrid.Children.Add(myButton);
打开App,查看更多内容
随时随地看视频慕课网APP