WPF将控件可见性绑定到另一个控件的焦点属性
我有一个显示项目列表的组合框,我想在其旁边放置一个按钮,该按钮会触发命令以查看所选项目的详细信息.到目前为止,一切都很好.现在,我希望按钮仅在组合框具有焦点(或处于编辑"模式,但不仅在弹出窗口处于打开状态时)可见.
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).
我认为我可以将按钮的可见性绑定到组合框的某些focus属性,如下所示:
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}}"/>
但是我没有办法知道我想要的控件是否集中.我看了一下FocusManager.FocusedElement,但是我不知道如何在绑定中获取想要的焦点控件.有没有办法在XAML中实现这一目标?
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?
好,让此功能按我的意愿工作的方法是:
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}}"/>
这里有两个关键因素:将按钮的可见性绑定到组合框的IsKeyboardFocusWithin属性,并将按钮的Focusable属性设置为false,否则当您单击它时它将折叠.
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.
希望这很有用.