How to get input on textchanged on winform - winforms

I want to wait to user input on winform. Without using textbox or other control. just the form it self handle the input.
I've try to add KeyPress and TextChanged Events to the form, both with no successes. What am I doing wrong?
thanks :)

Based on your comments, it sounds like you're asking why double clicking on a control to create an event handler works, but typing the exact same method signature doesn't. The reason for this is the designer generates code that winds up in the .Designer.cs file. If you look in there, you'll find (eventually -- there's a lot of code generated for forms...) a line linking the actual event the button raises to the handler method it generates; something like this:
button1.Click += button1_Clicked;
This is the magic that doesn't happen when you manually type the signature for button1_Clicked(object sender, EventArgs e) directly in the Form1.cs file.
But I might have misread your comments/question entirely, too.

If you want handle keyboard input on the Form:
Create a event handler for Form.KeyPress - event
Set property KeyPreview = true (Through designer for example)
Then before pressing keys be sure that Form have focused
Keyboard input on the Form level
About TextChanged event:
From MSDN:
This event is raised if the Text property is changed by either a
programmatic modification or user interaction.
So TextChanged event must be raised at least on the initialization of form, when .Text property be changed. And of course, everytime you change this property as: _myForm.Text = "my new form"
In your case TextChanged event not raised because(I assume) Event handler was added after InitializeComponent() method was called. Where (C#)this.Text = "MyForm" was called
TextChanged Event

Related

Add Handler method not being called when Routed Event is attached

I'm trying to create an attached behavior to add an auto-complete list to the standard TextBox control. My goal is that every time the TextChanged event is raised, my AutoCompleteBehavior class creates a popup and fills it with potential auto-complete results.
To get these results, my AutoCompleteBehavior declares the following event:
Public Shared ReadOnly AutoCompleteListRequestedEvent As RoutedEvent =
EventManager.RegisterRoutedEvent("AutoCompleteListRequested",
RoutingStrategy.Bubble,
GetType(AutoCompleteListRequestedEventHandler), GetType(AutoCompleteBehavior))
The above is meant to be an attached event, used like this:
<TextBox lib:AutoCompleteBehavior.AutoCompleteListRequested="EventHandlerHere"/>
The idea is that when TextChanged is raised, AutoCompleteBehavior.AutoCompleteListRequested is also raised, which asks the implementing program to supply a list of suggestions for the current input.
For this to work, I have to hook in to the TextBox.TextChanged event as soon as my attached event is attached to said TextBox. Per Microsoft I should be able to declare a sub Add*Handler and Remove*Handler where the "*" is the name of the attached event, and these would be called whenever the attached event is added or removed from an element.
So right below the event declaration I have:
Public Shared Sub AddAutoCompleteListRequestedHandler(TB As TextBox, handler As AutoCompleteListRequestedEventHandler)
'Code to hook into TextBox.TextChanged
End Sub
Public Shared Sub RemoveAutoCompleteListRequestedHandler(TB As TextBox, handler As AutoCompleteListRequestedEventHandler)
'Code to unhook fromTextBox.TextChanged
End Sub
My problem is AddAutoCompleteListRequestedHandler is never called. If I call TextBox.RaiseEvent to raise AutoCompleteListRequested, the event handler defined in XAML does get called (so the event is attached), but it seems my AddAutoCompleteListRequestedHandler is completely skipped.
As a final note, I found this question here which seems to be describing the same problem (my code is also in a dll just like his), but it's two years old and was never answered.
The XAML processor won't call your static methods when hooking up the event handler.
If you want to do something when the TextBox raises the TextChanged event, you would probably be better off implementing an attached behaviour and hook up to the TextChanged event in the PropertyChangedCallback or in the OnAttached() method depending on which kind of behaviour you create.
Please refer to my answer here for more information about attached behaviours.

Is there a possibility to programmatically trigger item action in ListView, like when you dobuleclick on it?

I was searching all over the place but I couldn't find an answer. I need to fire up an ListView item action, so it would rise the ItemActivate event. For now, it's only possible using ENTER key or double click... I would like to know if I could programmatically do that, something like :
listView.Items[int].Activate();
This doesn't work of course, because that function Activate() is not implemented there. For example, I couldn't find how to trigger buttons programmatically, but there it was, in the context menu which appears while you type:
buttonX.PerformClick();
...and it would trigger the button_click event. I wonder if there's something similar in the ListView control for triggering items inside of it ? I want it to raise this event programmatically and not by mouse doubleclick or Enter key on the keyboard...
private void myListView_ItemActivate(object sender, EventArgs e)
{
MessageBox.Show("hello");
}
According to the documentation, the EventHandler in the ListView should be public. So you can raise the event with:
myListView.ItemActivate(myListView, EventArgs.Empty);
This way everyone who subscribed to this event will get notified.
Another way, of course, is to directly call your method:
myListView_ItemActivate(this, EventArgs.Empty);
But this doesn't really classify as "raising the event", because you actually don't raise an event. You just call a method.

WPF close window when property in ViewModel changes

I was wondering if there was a way to close a window when a property in the view model changes. In my situation I have a login window with an Ok button bound to a LoginCommand so that the function Login executes when Ok is clicked. If the login is successful, I want the window to close.
Now I know I could do this by adding an event handler on my button, which calls a function like this:
private void Button_Click(object sender, RoutedEventArgs e)
{
DatabaseCredentialsViewModel vm = (this.DataContext as DatabaseCredentialsViewModel);
vm.Login();
if (vm.LoginSuccessful)
{
this.Close();
}
}
But I was wondering if there was a way to close the window when LoginSuccessful property changes without having an event handler on my button (I like working only with command binding and not having event handlers on Click event).
Thank you
Here's a similar question, which filled my need.
Basically, you use an attached property for your window, which binds to a bool? property on your VM. When the VM property is set to something non-null, the attached property sets the Window's DialogResult, which will automatically close the window.
If you want you can try this different approach.
You can do this by associating the OK button with a command. Create an event such as LoginSuccess and when then add a window.Close() to the list of event callback. Then you have only to raise the LoginSuccess event to close the windows.
In my opinion, this respect the MVVM pattern defining an event that can be used for other trigger and not only for closing windows.
You could do this fairly easily by creating an attached property or Behavior (from Blend SDK) that hooked into your Window.
I posted a sample behavior to the Expression Code Gallery which does something similar (though definitely different) - it prevents a window from being closed via a property on the VM. You could very easily adapt the code (included in the download) to just close the window on a property change.

WPF - Handling a RoutedEvent in the parent for a specific control instance

In my user control I have several textboxes e.g. Textbox1, Textbox2.
In the parent I only want to handle KeyDown events raised from Textbox1, not all Textbox
I have added a handler in the parent
this.AddHandler(TextBox.KeyDownEvent, new RoutedEventHandler(OnTextboxGoToPageKeyDown));
but of course this will handle all KeyDown events which I don't want.
Do I have to add some conditional logic in the RoutedEventHandler to check where the event was raised from?
or is there a better way?
What's the best way to do this?
Thanks.
The RoutedEventArgs in your OnTextboxGoToPageKeyDown has a property named Source which have a references to the Object who raised the event. You can ask for that property when you need to execute your logic.
HTH

How to register to/listen to richtextbox command's?

I'm creating a simple editor within our application using the WPF RichTextBox. Above it I've added the reguslar buttons like Bold, Italic, etc. These buttons use the RichTextBox's commands to set these properties, but next to these buttons, the commands also get send with CTRL+B, CTRL+I, etc. I want these buttons to represent the current state of the RichTextBox at the cursor. I already found out how to get this state and it works when I update this state on the SelectionChanged event. This event ofcourse isn't fired when Bold is toggled so there is no direct feedback.
I would like to know if there is a way to listen to the commands being called, without affecting its original behaviour or some other ideas to solve my problems.
I tried listening to the command the following way:
CommandBinding boldBinding = new CommandBinding(EditingCommands.ToggleBold, CommandExecuted);
_richTextBox.CommandBindings.Add(boldBinding);
and
private void CommandExecuted(object sender, ExecutedRoutedEventArgs e) {
UpdateProperties();
e.Handled = false;
}
This did update the properties, but the RichTextBox didn't seem to receive the command anymore.
I also tried to make my own commands on the control containing the RichTextBox, but when CTRL+B is pressed when the RichTextBox has focus, the original RichTextBox commands are called instead of the new one.
Many thanks in advance!
Liewe
In order to listen to the commands being called, you can use the events raised by CommandManager: Executed or PreviewExecuted.
If you change your XAML to:
<RichTextBox x:Name="_richTextBox" ...
CommandManager:PreviewExecuted="OnRichTextBoxCommand" ... />
you get the OnRichTextBoxCommand method called right before the command is executed. Unfortunately, using the Executed attached event does not work.
This method is called for each event, so you have to filter them:
private void OnRichTextBoxCommand(object sender, ExecutedRoutedEventArgs e) {
if (e.Command == EditingCommands.ToggleBold) {
UpdateProperties();
}
}
It may be even a bit more complex, as the current selection may not have changed when this method is called, so you have to post yourself a message, e.g. like this:
Dispatcher.BeginInvoke(new Action(UpdateProperties));
(if you reference already System.Core, you have the Action type, otherwise define a delegate taking no parameter and returning void, and use in instead.)

Resources