开发者

C# WPF - ComboBox

I'm working on a custom control that internally uses a ComboBox.

My problem is when the ComboBox is focused and has th开发者_开发问答e drop-down open, it appears to focus the entire control. I would like to automatically highlight the first item in the drop drown, but right now you have to push the Down key to do so.

Is there a way to programmatically Highlight the first item in a ComboBox (set the readonly IsHighlighted property to true)? I believe the concept of IsHighlight within a ComboBox is different than Focus. Also, I am binding via ItemsSource, so I have no reference to ComboBoxItems.


Here's a way of doing it, although it might not cover all the cases - but you didn't provide too many details (for example, what happens when there is already an element selected? Do you still want to select the first element in the list? The code below will highlight the first element only when there is no selection in the combobox. To make it always select the first element, the DropDownOpened event should be handled too).

public MainWindow()
{
    InitializeComponent();
    combobox.ItemContainerGenerator.StatusChanged += new EventHandler(ItemContainerGenerator_StatusChanged);
}

void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
{
    if (combobox.ItemContainerGenerator.Status == System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated)
    {
        (combobox.ItemContainerGenerator.ContainerFromIndex(0) as ComboBoxItem).Focus();
    }
}

(Hope I understood correctly and this is what you want to do).


It might not be what you are looking for but if you set mycombo.SelectedIndex = 0 then mycombo.IsDropDownOpen = True it should open it up and have the first item selected. It will be highlighted but will also be the value in the combobox as well. I'm not sure if this is not the desired effect though..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜