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..et开发者_StackOverflow社区c)
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
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...
Try to use the FocusManager
class. When your TextBox has lost Keyboard Focus, it still has Logical Focus, if it is inside the Focus Scope. Classes in WPF which are focus scopes by default are Window, MenuItem, ToolBar, and ContextMenu.
So using this will give you the result -
FocusManager.GetFocusedElement(winodw1); //Name of the window
For more details, read this - http://msdn.microsoft.com/en-us/library/aa969768.aspx
精彩评论