2016-07-25 74 views
0

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

<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> 

但在这种情况下,每个复选框后添加按钮。你有什么想法,怎么做只有一次?预先感谢您)

+0

编辑'组合框本身的Template'财产。在VS中,右键点击CB,选择Edit Template(编辑模板) - Edit copy(编辑副本),然后在该模板中添加Button。 – ASh

+0

您的问题尚不清楚 - 您是否想将该按钮作为ComboBox中的一个选项? 你想创建自己的包含按钮的ComboBox吗? 你想让组合框中的每个选项都包含一个按钮吗? – MichaelThePotato

+0

我想添加一个按钮作为第一个组合框项目,并且所有下一个项目必须是ItemsTemplate中的项目 –

回答

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); 
} 
1
  1. 权设计师表面/或文档大纲在左侧外设计师表面>编辑模板>编辑复制点击组合框。

  2. 这会产生一些样式Window.Resources下,找到ItemsPresenter,按照下图用StackPanelButton包装它:

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