绑定ItemsSource时如何向wpf列表框中添加按钮

时间:2018-07-23 06:09:34

标签: c# wpf button listbox

我现在有这个:

    <ListBox ItemsSource="{Binding Items}">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid/> 
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
    </ListBox>

但是我需要这样的东西 THIS. 不幸的是,当我以编程方式添加按钮

ListBox.Items.Add(button);

它引发错误-

  

在使用ItemsSource时操作无效

2 个答案:

答案 0 :(得分:0)

像这样使用

var myButton = new Button()
{
   Height = 25,
   Width = 80
   Content = "+",
   Background = Brushes.Gray
}

UniformGrid.Children.Add(myButton);

答案 1 :(得分:0)

CompositeCollection正是您需要的。以下是XAML个示例:

<Window ...>
    <!-- You should define your ItemsSource in resources-->
    <Window.Resources>
        <CollectionViewSource x:Key="Names" Source="{Binding Names}" />
    </Window.Resources>

    <Grid>
        <ListBox>
            <ListBox.ItemsSource>
                <CompositeCollection>
                    <CollectionContainer Collection="{Binding Source={StaticResource Names}}" />

                    <ListBoxItem Foreground="Red">Add new...</ListBoxItem>
                </CompositeCollection>
            </ListBox.ItemsSource>

            <!-- Here you can customize everything you want -->
        </ListBox>
    </Grid>
</Window>