如何在WPF中以编程方式更改ComboBox列表以在对象上方显示?

时间:2016-03-22 21:11:11

标签: c# .net wpf wpf-controls

如何将Combobox列表更改为始终仅使用C#(无XML)显示在ComboBox对象上方? 在这种情况下, DropDownStyle 属性似乎不可用。

1 个答案:

答案 0 :(得分:0)

首先,请注意DropDownStyle仅适用于Windows Forms ComboBox,而非WPF ComboBox

所以,你需要用WPF以不同的方式解决这个问题。基本上,WPF使用样式和模板来确定控件的可视方面。

对于这个特殊问题,您需要编辑ComboBox的Placement控件的Popup属性,该属性是ControlTemplate的一部分。

以下是如何执行此操作的示例(将其放在代码隐藏中):

protected override void OnInitialized(EventArgs e)
{
    base.OnInitialized(e);

    // create a combo box
    var comboBox = new ComboBox
    {
        HorizontalAlignment = HorizontalAlignment.Center,
        VerticalAlignment = VerticalAlignment.Center,
        Width = 200
    };

    // add some items
    comboBox.Items.Add(new ComboBoxItem { Content = "Apple" });
    comboBox.Items.Add(new ComboBoxItem { Content = "Banana" });
    comboBox.Items.Add(new ComboBoxItem { Content = "Orange" });

    // add the combo box to your window
    AddChild(comboBox);

    // apply the control template
    comboBox.ApplyTemplate();

    // obtain the popup (which is named "PART_Popup") from the control template
    var controlTemplate = comboBox.Template;
    var popup = (Popup)controlTemplate.FindName("PART_Popup", comboBox);

    // set the placement of the popup
    if (popup != null) popup.Placement = PlacementMode.Top;
}

最后一点:我怎么知道有一个名为" PART_Popup"的弹出窗口?有几种方法:

  1. 您可以使用Visual Studio设计器为任何内置控件实际生成标准控件模板的副本。具体来说,在窗口中放置一个控件(例如,ComboBox),转到Document Outline,右键单击ComboBox,然后选择" Edit Template ..."。
  2. 您可以使用Snoop utility实际查看"视觉树"窗口中的控件/图形。