Keyboard command binding on WPF Inside User Control - c#

I am trying witth the following code for keyboard command binding on WPF window:
RoutedCommand cmndSettings = new RoutedCommand();
cmndSettings.InputGestures.Add(new KeyGesture(Key.S, ModifierKeys.Alt));
CommandBindings.Add(new CommandBinding(cmndSettings, mnuSettings_Click));
private void mnuSettings_Click(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("key pressed");
}
This is working fine if I place this code inside a xaml Window's cs file. But, if I place it inside a user control's cs file, which dynamically loaded in a parent window, keyboard events aren't triggering there at all. What I need to do to get it working inside a user control plz? Thanks.

To work with controls under a user control, its very important that, the containers/user control is focus-able properly. otherwise, may not work.

Related

Showing/Hiding a control from within another control

I have got a Windows forms application with a main application form and two controls I added to my main form.
The first control has got a login button. When that button is pressed, I want to hide control1 and show control2, which is currently hidden.
Hiding control1 works by using this.Hide() in the onClick event of the login button, but I have so far been unable to find a way to reference control2 and call .Show()
How can I show control2 from within the onClick event of the login button?
EDIT:
Hope the below information helps.
Controls:
LoginMenu.cs - Has all of the control's code in it. - Control name in MainForm.cs is loginMenu1
TicketSearch.cs - Has all of the control's code in it. - control name in MainForm.cs is ticketSearch1
After adding all controls, I rebuilt the project and dragged them into the main form from the tools menu.
The code for the login button is in LoginMenu.cs
public partial class LoginMenu : UserControl
{
public LoginMenu()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
*CODE HERE*
}
void ButtonLoginClick(object sender, EventArgs e)
{
*CODE HERE*
try
{
HttpWebResponse response =
(HttpWebResponse)loginTest.GetResponse();
}
catch (System.Exception ex)
{
if (ex.Message.Contains("401") == true)
{
*CODE HERE*
}
else if (ex.Message.Contains("403") == true)
{
*CODE HERE*
//Hide login control. This works
this.Hide();
//This is where I want to show the control ticketSearch1
}
}
}
}
Thanks to those who tried to help. I learnt something new today.
For some reason, I don't quite understand I could not access the controls in MainForm.cs from LoginMenu.cs even though they are in the same namespace and the control 'Modifiers' property is set to 'Public'.
I resolved this by adding the following method call to my login button onClick action to reference the control I wanted Form.ActiveForm.Controls.Find("ticketSearch1", true)[0].Show();
But it should work.
Look at the properties of Control2 and pick the name (or set a name) under the line "(Name)".
then you should:
private void button_Click(object sender, EventArgs e)
{
firstcontrol.Hide();
secondcontrol.Show();
}
it should work.
Maybe you failed with the placing of the control. So look what happens if you start your programm with the first control hidden and the second one shown. And try to hide the second control and show the first.
There must be the problem.
Did you place your Control via "Toolbox"?
Or do you call your Control via code?
EDIT:
Referring to your inserted Code, it seems, that you call this code in your Usercontrol.
So you need to set the second Usercontrol to "Public". When you click on it and go to the Properties, you choose "Mofifiers" and set it to public.
Now you should look for the (Name) Attribute in his properties.
Then just add:
NameOfYourSecondControl.Show();
This will fix your problem.

Focus Handling in WPF Custom control (Set focus on WPF Custom Control from view model)

I'm working on a WPF Application using MVVM.
I have a view with tabs, and a listbox (which is not part of the tabControl) which displays all the validation errors on the view (using INotifyDataErrorInfo interface).
What I want to achieve: Once I click on an item within the listbox, the focus goes to the tab with the corresponding control and set focus on that control.
For example, I have a validation error for First Name, so when I click on the item within the listbox describing the validation error for the first name, I want to switch to the tab where the First Name textbox is located and set focus for that textbox. Now, I followed what is written here:
Set focus on textbox in WPF from view model (C#)
especially Zamotic reply ( he had the same situation with tabs as I have).
Now, the described situation above works well for me with the textboxes: it indeed goes to the First Name textbox and sets the focus for it.
The problem is that I have a WPF custom control in one of my tabs, and when I click on a validation error within the listbox regarding this custom control, it indeed goes to the correct tab, but no focus is set to the custom control.
The custom control consists of a textBox, and I want the focus to be set to this textbox.
So, how do I handle Focus in a custom control so it fits the describes requirement above?
Here is the code for my custom control (the part of the code where I try to handle the focus):
public class NumericUpDownControl : Control
{
static NumericUpDownControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(NumericUpDownControl), new FrameworkPropertyMetadata(typeof(NumericUpDownControl)));
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
AttachToVisualTree();
this.GotFocus += new RoutedEventHandler(GetFocusHandler);
this.LostFocus += new RoutedEventHandler(LostFocusHandler);
}
private void GetFocusHandler(object sender, RoutedEventArgs e)
{
TextBox.Focus();
this.Focusable = false;
}
private void LostFocusHandler(object sender, RoutedEventArgs e)
{
IncreaseButton.Focus();
}
Textbox is the one set in the custom control Themes folder in Generic.xaml
var textBox = GetTemplateChild("valueBox") as TextBox;
if (textBox != null)
{
TextBox = textBox;
So, how do I handle the focus to achieve what I have already acheived for textboxes?
Edit 1: By the way, IncreaseButton is another control (which is a button) that my custom control consists of. When my custom control goes out of focus, I want to draw the focus off the textbox, so I just set it for that mentioned button.
Edit 2: In my view, I have a tab with the mentioned custom control. In my view model, I have a property called
public bool IsAgeFocused
And in the View I've written the following:
<numeric:NumericUpDownControl
x:Name="numericUpDownBox"
uiExtension:FocusExtension.IsFocused="{Binding IsAgeFocused}"
Focus Extension is the same class (without any additional info) like in the link:
Set focus on textbox in WPF from view model (C#)
The version described in Zamotic post (with the visibility part).

Drag&Drop with WPF WebBrowser control - Drop event not firing

I'm currently in need to capture the Drop event of the WPF WebBrowser control but for some reason it's not firing. If I drag a .pdf file into the control it's being displayed but the Drop event isn't firing.
Small sample:
Create a new WPF project, add this inside the XAML code of the MainWindow.xaml between the Grid tags:
<WebBrowser Name="test" />
And change the MainWindow.xaml.cs so it looks like this:
public MainWindow()
{
InitializeComponent();
test.AllowDrop = true;
test.Drop += test_Drop;
}
void test_Drop(object sender, DragEventArgs e)
{
MessageBox.Show("Hi");
}
The messagebox will not be displayed when you drop a PDF file inside the WebBrowser control. What am I doing wrong?
You should try test.AllowDrop = true;. Take a look at this Tutorial
Edit:
After a few tries and a little research i found out that no Drag event will be fired at all. But maybe this question helps you here

Disabling child control events

The child controls of my custom control are obstruction the mouse events in my custom control. I have worked through the accepted answer and the answer at the bottom of this thread...
exposing-events-of-underlying-control
I haven't gotten them to work (the answer at the bottom seemed most straight forward to me). But really I would like to disable the events of them altogether. I have a pictureBox and a label, I don't need to interact with either of the child controls. Is there a way to disable them so they wont interfere with the events of my custom control?
Edit:
I'm using the custom control to gather and process a number of things and make them available as properties. When I click on it, I need to access to the properties. When the event happens at the child control, I don't have access to the propertied of my custom control. The following code is in my form...
public void Form1_MouseDown(object sender, MouseEventArgs e)
{
var myControl = sender as SubstanceViewer;
richTextBox1.Text = myControl.substanceInfo;
}
so I will need to access the properties of the parent control.
If you need the the events that are normally trapped by the child controls to be handled by the custom control itself, then simply wire up those events at run-time in the constructor of the custom control.
For example if you needed the MouseMove() event of the PictureBox and Label to fire the already wired up event of the UserControl:
public partial class SomeUserControl : UserControl
{
public SomeUserControl()
{
InitializeComponent();
this.pictureBox1.MouseMove += SomeUserControl_MouseMove;
this.label1.MouseMove += SomeUserControl_MouseMove;
}
private void SomeUserControl_MouseMove(object sender, MouseEventArgs e)
{
}
}
Be aware, though, that since different controls are firing the same handler you'll need to take that into account. For example, the e.X and e.Y values in the handler above would be relative to the source control.
*You can also wire these events up at design-time using the IDE itself, but I thought code better illustrated the solution.

Why does setting focus in the OnNavigatedTo() event not set focus?

I've got this code in a pages OnNavigatedTo() event:
if (string.IsNullOrWhiteSpace(textBoxGroupName.Text))
{
textBoxGroupName.Focus(FocusState.Programmatic);
}
...but textBoxGroupName does not have focus when the page displays. Why not?
OnNavigatedTo happens to early in the page lifetime for setting the focus to work. You should call your code in the Loaded event:
private void MainPage_OnLoaded(object sender, RoutedEventArgs e)
{
if (string.IsNullOrWhiteSpace(textBoxGroupName.Text))
{
textBoxGroupName.Focus(FocusState.Programmatic);
}
}
Of course you need to setup the handler in your .xaml file (I've omitted the other attributes in the Page element:
<Page
Loaded="MainPage_OnLoaded">
Only controls that are contained within the GroupBox control can be selected or receive focus. Seems like you are not using GroupBox correctly.
From MSDN
The complete GroupBox itself cannot be selected or receive focus. For more information about how this control responds to the Focus and Select methods, see the following Control members: CanFocus, CanSelect, Focused, ContainsFocus, Focus, Select.
Hint:
You maybe want to use the Controls property to access the child controls:
if (string.IsNullOrWhiteSpace(textBoxGroupName.Text))
{
var child_TextBox = textBoxGroupName.Controls["myTextBox"]
if(child_TextBox.CanFocus)
child_TextBox.Focus(FocusState.Programmatic);
}

Categories

Resources