【问题标题】:WPF routed command enabling works with menu but not with a buttonWPF 路由命令启用适用于菜单,但不适用于按钮
【发布时间】:2012-05-27 20:30:35
【问题描述】:

在以下示例中,当文本获得焦点而不是按钮时,菜单被启用。我只用按钮和文本框试过了,但行为是一样的。

<Window x:Class="WpfPopup.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<DockPanel>
    <Menu DockPanel.Dock="Top">
        <MenuItem  Command="ApplicationCommands.Paste" />
    </Menu>
    <TextBox BorderBrush="Black" BorderThickness="2" Margin="25" TextWrapping="Wrap" x:Name="text1" Height="58" Width="203" >
        The MenuItem will not be enabled until
        this TextBox gets keyboard focus
    </TextBox>        
    <Button Content="Button" Height="23" Name="button1" Width="93" Command="ApplicationCommands.Paste" />
</DockPanel>

【问题讨论】:

    标签: wpf command


    【解决方案1】:

    有两种简单的方法可以解决这个问题:

    1) 使用 FocusManager.IsFocusScope:

        <Button Content="Button" Height="23" Name="button1" Width="93" Command="ApplicationCommands.Paste" FocusManager.IsFocusScope="True"/>
    

    2) 手动设置按钮上的CommandTarget:

    <Button Content="Button" Height="23" Name="button1" Width="93" Command="ApplicationCommands.Paste" CommandTarget="{Binding ElementName=text1}" />
    

    您可能想知道为什么这适用于菜单项?如果您阅读FocusManager.IsFocusScope 附加属性的文档,您将得到答案:

    默认情况下,Window 类和 Menu 一样是焦点范围, ContextMenu 和 ToolBar 类。作为焦点范围的元素 已将 IsFocusScope 设置为 true。

    当你不知道的时候会很困惑!

    【讨论】:

    • 非常感谢 - 非常有启发性。我开始了解为什么按钮的处理方式不同。我注意到的一件事是没有 FocusManager.IsFocusScope="True" 按钮将焦点从文本框移开,而菜单则没有。应用该属性时,按钮的行为类似于菜单。我想当你考虑它时这是有道理的——当一个可以接受它的控件获得焦点时,该命令应该被启用。但是,我使用 WPF 的次数越多,它就越像黑魔法。
    • 通常您会将属性放在面板上——例如包含按钮的 StackPanel。如果它有帮助,那么在命令章节(第 9 章)的 C# 2010 中的 Pro WPF 一书中有很多相关内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 2017-03-14
    • 2011-03-28
    • 2021-05-02
    • 2020-01-13
    • 1970-01-01
    相关资源
    最近更新 更多