Search code examples
c#wpfrouted-commands

Clear MenuItem, with clear command


hi i'm a "very" beginner in wpf i'm trying to make a menu item "Clear", it should clear the text in the focused text box, actually i could not find a built in command that does the job like (copy,paste,cut..etc)

is there one built in or do i have to make a custom routed command, and if so i've tried but failed, and need ideas

i've made the ClearCommandExecuted logic, but the problem is with "CanExecute" i tried to access the Keyboard.FocusedElement there, but failed because the focused element is the menu item it self when it's clicked !!!!

please help thanks


Solution

  • You need to use one of the arguments passed into your 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;
            } 
        }
    

    I hope this is enough to get you headed in the right direction...