views:

267

answers:

2

Hi !

I need to write a custom WPF control that should look like a ComboBox with extended items search feature. For this purpose I'd like to have a TextBox and a Popup with a search TextBox and a ListBox.

My first question is if it's a good decision to inherit from Selector, or rather ComboBox ?

The second question is where can I find a good example of this.. the only solution seems to be disassembling the Microsoft's library and look approximately what they are doing.

Other questions:

  1. How should I handle events? e.g. Button click in a Template. Should I look it up in the Template and register the events in that way, or can I register it directly in XAML like Click="PART_Button1CLick" ?

Thank you guys !

A: 

I think you're on the right track. You could have a TextChanged event on the TextBox, and after the text changes, if there are at least 3 characters, you spawn your popup with the listbox of results, and the listbox has its SelectionChanged event set to set the text of the TextBox and kill its parent popup. You should probably check to see if there's a popup already created, and kill it if a new character comes in. You might even put the spawning of the popup on a timer, so if they rapidly type five characters, you only create a popup after a second of downtime (avoiding the two extraneous popups).

I don't know of a good example, but I've done something similar (possibly even exactly this, I don't remember), and it really won't be that difficult.

The only thing that confuses me is when you say:

For this purpose I'd like to have a TextBox and a Popup with a search TextBox and a ListBox.

I don't understand the second TextBox there. You should only need the first.

Mike Pateras
A: 

OK This is what I've done:

XAML ControlTemplate in Themes/Generic.XAML:

<Style TargetType="{x:Type local:MyControl}">        
    <Setter Property="Template">
    ... 
    </Setter>
</Style>

Control itself:

[TemplatePart(Name = MyControl.partSelectedTextBox, Type = typeof(TextBox))]
public class MyControl : Selector
{

public override void OnApplyTemplate()
{
    ...
    if (_txtSelected == null)
    {
        _txtSelected = base.GetTemplateChild(partSelectedTextBox) as TextBox;
        if (_txtSelected != null)
        {
            _txtSelected.MouseLeftButtonUp += new MouseButtonEventHandler(PART_txtSelected_MouseLeftButtonUp);
        }
    }
    ...
    base.ApplyTemplate();
}

}
PaN1C_Showt1Me