【问题标题】:Clear MenuItem, with clear command清除 MenuItem,使用 clear 命令
【发布时间】:2011-07-22 16:19:59
【问题描述】:

嗨 我是 wpf 的“非常”初学者 我正在尝试使菜单项“清除”,它应该清除焦点文本框中的文本, 实际上我找不到像 (copy,paste,cut..etc) 这样的内置命令

是否有内置的,或者我是否必须制作自定义路由命令,如果有 我试过但失败了,需要想法

我已经制定了 ClearCommandExecuted 逻辑,但问题在于“CanExecute” 我试图在那里访问 Keyboard.FocusedElement ,但失败了,因为当它被点击时,焦点元素是它自己的菜单项!!!!

请帮忙 谢谢

【问题讨论】:

  • 你可以发布你已经拥有的代码吗?

标签: c# wpf routed-commands


【解决方案1】:

您需要使用传递给 CanExecuteQuery 的参数之一:

    private void ClearCommandBindingCanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        // e.Source is the element that is active,
        if (e.Source is TextBox) // and whatever other logic you need.
        {
            e.CanExecute = true;
            e.Handled = true;
        }
    }

    private void ClearCommandBindingExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        var textBox = e.Source as TextBox;
        if (textBox != null)
        {
            textBox.Clear();
            e.Handled = true;
        } 
    }

我希望这足以让你朝着正确的方向前进......

【讨论】:

  • 非常感谢,这很有帮助,抱歉回复晚了
【解决方案2】:

尝试使用FocusManager 类。当您的 TextBox 失去键盘焦点时,如果它在焦点范围内,它仍然具有逻辑焦点。 WPF 中默认为焦点作用域的类有 Window、MenuItem、ToolBar 和 ContextMenu。

所以使用它会给你结果 -

FocusManager.GetFocusedElement(winodw1); //Name of the window

欲了解更多详情,请阅读这篇文章 - http://msdn.microsoft.com/en-us/library/aa969768.aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 1970-01-01
    • 1970-01-01
    • 2018-04-22
    • 2016-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多