WPF在组合框中添加按钮

时间:2016-07-25 06:35:06

标签: wpf xaml combobox itemtemplate

我想在组合框中添加按钮,其中包含ItemTemplate。首先,我试过的是:

<ComboBox Name="oilWells_comboBox"
          Style="{StaticResource MMComboBox}"
          MaxWidth="100"
          ItemsSource="{Binding DataContext.OilWellCollection, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:MainWindow}}"
          Margin="0">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
                <CheckBox IsChecked="{Binding Path=IsDisplay}" Checked="FilterDataGrid" Unchecked="FilterDataGrid">
                    <CheckBox.Content>
                        <TextBlock MinWidth="100" Text="{Binding Path=Name}" HorizontalAlignment="Center" TextWrapping="Wrap" TextTrimming="CharacterEllipsis"/>
                    </CheckBox.Content>
                </CheckBox>
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
    <Button Content="Clear" Height="20" HorizontalAlignment="Stretch"></Button>
</ComboBox>

但是我有一个例外,它说我不能添加要控制的项目,它有ItemTemplate。第二个是:

<ComboBox Name="oilWells_comboBox"
          Style="{StaticResource MMComboBox}"
          MaxWidth="100"
          ItemsSource="{Binding DataContext.OilWellCollection, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:MainWindow}}"
          Margin="0">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
                <CheckBox IsChecked="{Binding Path=IsDisplay}" Checked="FilterDataGrid" Unchecked="FilterDataGrid">
                    <CheckBox.Content>
                        <TextBlock MinWidth="100" Text="{Binding Path=Name}" HorizontalAlignment="Center" TextWrapping="Wrap" TextTrimming="CharacterEllipsis"/>
                        <Button Content="Clear" Height="20" HorizontalAlignment="Stretch"></Button>
                    </CheckBox.Content>
                </CheckBox>
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

但在这种情况下,按钮会在每个复选框后添加。你有什么想法,如何只做一次?提前谢谢你)

2 个答案:

答案 0 :(得分:1)

  1. 右键单击设计器表面中的ComboBox /或设计器表面外部左侧的Document Outline&gt;编辑模板&gt;编辑副本。

  2. 这会在Window.Resources下生成一些样式,找到ItemsPresenter并将其与StackPanelButton一起打包,如下所示:

    <StackPanel Grid.ColumnSpan="2">
       <Button Content="Additional"/>
       <ItemsPresenter x:Name="ItemsPresenter" KeyboardNavigation.DirectionalNavigation="Contained" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
    </StackPanel>
    

答案 1 :(得分:0)

在Windows加载的事件中尝试这个,它应该可以工作。

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    Button b = new Button();
    b.Content = "My Button";
    b.Click += new RoutedEventHandler(MyBtn_Click);
    oilWells_comboBox.Items.Add(b);
}