Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF bind a control visibility to the focused property of another control

I have a combobox that displays a list of items, and I want to place a button next to it which triggers a command to see the details of the selected item. So far, so good. Now I want the button to be visible only if the combobox has focus (or is in "edit" mode, but not only when the popup is open).

I thought I could bind the visibility of the button to some focus property of the combobox, something like this:

<Button Content="Details" Visibility="{Binding ElementName=elementListComboBox,
Path=IsFocused, Converter={StaticResource Bool2VisibilityConverter}}"/>

But I found no way to know if the control I want is focused or not. I looked at the FocusManager.FocusedElement, but I don't know how to get the focused control I want inside the binding. Is there a way to achieve this in XAML?

like image 886
Hannish Avatar asked Dec 28 '12 11:12

Hannish


1 Answers

Ok, the way to get this working as I wanted is this:

 <Button Command="{Binding SomeCommand}"
         Content="Details" 
         Focusable="False"
         Visibility="{Binding ElementName=elementListComboBox, 
                      Path=IsKeyboardFocusWithin, 
                      Converter={StaticResource Bool2VisibilityConverter}}"/>

Two key factors here: bind the button's visibility to IsKeyboardFocusWithin property of the combobox, and set the button's Focusable property to false, else it will get collapsed when you want to click on it.

Hope this is useful.

like image 118
Hannish Avatar answered Nov 15 '22 08:11

Hannish