views:

372

answers:

1

Hi Friends. I am a little new to wpf.

I wanna write a control similar to ComboBox and I'm wondering if anybody knows how to get noticed when a user clicks not inside the combobox boundries. Because combobox closes it's dropdown in this situation.

+1  A: 

You can define your own custom control and control template with a textbox and a popup. Then override the OnApplyTemplate method of your control and find the popup using:

var popup = this.GetTemplateChild("PART_Popup") as Popup;

Now you can decide when to display or hide the popup by setting its IsOpen properties to true or false.

To find out if a user clicks on some other part of you UI just subscribe to the PreviewMouseDown event on your control's parent (somewhere in your control initialization code):

var parent = VisualTreeHelper.GetParent(this) as UIElement;
if(parent != null) {
    parent.PreviewMouseDown += MouseDownHandler;
}

Now you should get notified whenever a user clicks anywhere inside your control's container. You can also use the VisualTreeHelper.GetParent(...) recursively to get to the root element (such as a window) until it returns a null.

The popup will not be in the same visual tree and therefore you need to define mouse event handlers for the popup's root element if you want to know when a user clicks inside the popup.

Pavel