WPF 将控件可见性绑定到另一个控件的焦点属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14068606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 06:48:14  来源:igfitidea点击:

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

wpfxamlbindingcontrols

提问by Hannish

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?

但是我发现无法知道我想要的控件是否集中。我查看了 FocusManager.FocusedElement,但我不知道如何在绑定中获得我想要的焦点控件。有没有办法在 XAML 中实现这一点?

回答by Hannish

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.

这里有两个关键因素:将按钮的可见性绑定到组合框的 IsKeyboardFocusWithin 属性,并将按钮的 Focusable 属性设置为 false,否则当您想要单击它时它会折叠起来。

Hope this is useful.

希望这是有用的。