Accessing Child control event from parent level wpf - c#

I have a user control named myControl. I have rendered another user control named dialog inside myControl as <uc:dialog x:Name="dialog"> .
I have a button named as myButton inside the dialog user control. I need to get the lostfocus event of myButton from the parent level .ie,myControl code behind.How can I get that? Which is the best way to do that?
var myButton= dialog.FindName("myButton") as Button;
if (myButton!= null)
{
myButton.LostFocus += myButton;
}
I tried like this. But it doesn't work.Why?

You could define such an Event in your UserControl.
Then just register for this event.
public event EventHandler ButtonLostFocusEvent;
private void Button_LostFocus(object sender, RoutedEventArgs e)
{
EventHandler testEvent = this.ButtonLostFocusEvent;
// Check for no subscribers
if (testEvent == null)
return;
testEvent(sender, e);
}

Related

User Control Form Click event not clicking on label C#

I have a problem with User form Click that I am trying to make in C# using a usercontrol.
It consists of a picturebox and a label. I want to call the click event but the picturebox and the label don't do anything when I click them. Only the background area of the usercontrol does what I want it to do. Any ideas?
here's my code
for (int i = 0; i < listitems2.Length; i++)
{
listitems2[i] = new declined();
//adding sample data to each dynamic user
listitems2[i].dicon = dicon[i];
listitems2[i].did = did[i];
listitems2[i].dname = dname[i];
//adding data to flow layout panel
flowLayoutPanel2.Controls.Add(listitems2[i]);
// below line will assing this (usercontrolclick) event to every user control created dynamically
listitems2[i].Click += new System.EventHandler(this.UserControl_Click);
}
for click function
void UserControl_Click(object sender, EventArgs e)
{
string ctrlName = ((UserControl)sender).Name;
applicable obj = (applicable)sender;
studid.Text = obj.id;
studname.Text = obj.name;
pictureBox1.Image = obj.icon;
}
You added OnClick handler to your UserControl, so only clicks made on UserControl will be registered. To enable Click event for all the controls on your form, you need to add your click handler to all other controls.
But, according to your code, you're adding click handling on form where your control is located. In this case, you cannot register clicks on control from "outside" (you can by making Label and PictureBox controls public and adding handlers for their OnClick events but that is wrong way to do it)
My suggestion is to make custom event on your form and raise it on Form, Label and PictureBox click, and then make handler for that event on form which holds your UserControl.
Something like this:
//make custom eventHandler on your UserControl
[Browsable(true)]
public event EventHandler UserControlClicked;
//constructor
public UserControl1()
{
InitializeComponent();
//after intialize compoment add same handler for all three controls
this.Click += ControlClicked;
this.pictureBox1.Click += ControlClicked;
this.label1.Click += ControlClicked;
}
//this method will "catch" all clicks
private void ControlClicked(object sender, EventArgs e)
{
//raise event
UserControlClicked?.Invoke(this, e);
}
and on form where your custom control is, add handler for UserControlClicked (maybe with cast, I don't know what listItems2[i] contains):
listitems2[i].UserControlClicked+= new System.EventHandler(this.UserControl_Click);
or maybe like this (with casting)
(listitems2[i] as UserControl1).UserControlClicked+= new System.EventHandler(this.UserControl_Click);
and handle the rest in your UserControl_Click method like before

User control click event not working when clicking on text inside control?

I have a user control called GameButton that has a label inside it. When I add the user control to my form, and add a click event to it, its triggered when you click on the background of the custom button, but not the text in the label? How would I fix this without adding a bunch of click events inside the user controls code?
edit: UI framework: winforms
If I am understanding you properly, your GameButton usercontrol will fire the event when clicked on, but not when the label is clicked on -- and you want both. This is because the label (a control) is on top of the background. Therefore, you need to register your label with the click event as well. This can be done manually in the designer or programmatically for each control on the page.
If you want to do EVERY control in the UserControl, put this into the UserControl's OnLoad event and you can use the same click event for every control:
foreach (var c in this.Controls)
c.Click += new EventHandler(yourEvent_handler_click);
public void yourEvent_handler_click (object sender, EventArgs e){
//whatever you want your event handler to do
}
EDIT: The best way is to create the click event handler property in the user control. This way, every time you add/remove a click event to your user control, it adds/removes it to all the controls within the user control automatically.
public new event EventHandler Click {
add {
base.Click += value;
foreach (Control control in Controls) {
control.Click += value;
}
}
remove {
base.Click -= value;
foreach (Control control in Controls) {
control.Click -= value;
}
}
}
This is as per another post:
Hope this helps!
You can create a new method and assign all the controls to it
private void Control_Click(object sender, EventArgs e)
{
this.OnClick(e);
}
This will raise main control(or usercontrol) event.
Set the "enable" property of your labels "False, then mouse events will work in user control.
You can make the events in the controls of the User Control call the event of the User Control like that:
foreach (Control c in this.Controls)
{
c.Click += (sender, e) => { this.OnClick(e); };
c.MouseUp += (sender, e) => { this.OnMouseUp(e); };
c.MouseDown += (sender, e) => { this.OnMouseDown(e); };
c.MouseMove+= (sender, e) => { this.OnMouseMove(e); };
}
Just put it in the constructor. This way when an event is added to the User Control using polymorphism it will work
Here This control has 4 child control like 3 label and 1 picturebox.
so add this.onClick(e) in c# or Me.onClick(e) in vb.net on there on click event
like this
Private Sub rate_lab_Click(sender As Object, e As EventArgs) Handles rate_lab.Click
Me.OnClick(e)
End Sub
So wherever click inside user control the click event act as single event

Call a function of parent aspx page from web user control

i have a aspx page on it i'm dynamically adding the web user controls in a placeholder. and know i have cancel button on the one user control and on click of that Cancel button i want to load other user control inside the aspx page (placeholder).
how can i do that, if i create an event handler in usercontrol then that become null.
thanks
A user control should never, ever have any kind of dependency to the page where it lives. Add an event to the control and fire it from the Cancel button event handler.
public event EventHandler CancelClicked;
protected Cancel_Click(object sender, EventArgs e)
{
if(CancelClicked != null)
{
CancelClicked(this, e);
}
}
From your page, subscribe to the controls's CancelClicked event and do whatever operation should be done on that other user control.
I believe the best way to achieve this would to create an event in the user control that is fired when you need it to communicate, then in the page you can subscribe to this event.
Your User Control
Put this in your control as an event variable.
public event EventHandler CancelRequested;
Then in the cancel button click event :
CancelRequested(this, new CommandEventArgs("CancelClicked", SomeVariable));
Your Page (or parent)
Then subscribe to the event in the parent page like this (when you dynamically add it in):
ctrlYourControl.CancelRequested += new EventHandler(ctrlYourControl_CancelRequested);
Declare the event handler :
void ctrlYourControl_CancelRequested(object sender, EventArgs e)
{
// display other user control
}
Add this event to your user controls:
public event EventHandler CancelClicked;
Now, this method on your parent aspx page.
public void OnCancelClicked (object sender, EventArgs data)
{
// do your stuffs like loading other controls and
// whatever when event fired
}
When you are loading your user control dynamically, add this:
var someControl = LoadControl(#"~\SomeControl.ascx") as SomeControl;
someControl.CancelClicked += new EventHandler(OnCancelClicked);
And on your user controls:
public void btnCancel_Click(object sender, EventArgs e)
{
if(CancelClicked != null)
{
CancelClicked(this, e);
}
}
This should do !

Which control has been clicked?

I have a problem with MouseEvents on my WinForm C# application. I want to get ALL mouse clicks on my application.
How to determine which control has been clicked ?(I'm beginner C#)
Try this:
private void Control_Clicks(object sender, EventArgs e)
{
Control control = (Control)sender; // Sender gives you which control is clicked.
MessageBox.Show(control.Name.ToString());
}
This, this or this may help.
Hope it helps.
private void Form1_Load(object sender, EventArgs e)
{
SetupClickEvents(this);
}
/// <summary>
/// This will loop through each control within the container and add a click handler to it
/// </summary>
/// <param name="container">The container whose children to handle clicks for</param>
private void SetupClickEvents(Control container)
{
foreach(Control control in container.Controls)
{
control.Click += HandleClicks;
}
}
private void HandleClicks(object sender, EventArgs e)
{
Control control = (Control)sender;
MessageBox.Show(string.Format("{0} was clicked!", control.Name));
}
If you're doing Windows Forms, you have several options :
Hook mouse event, and after figure out if the clicked component actually makes part of your application
You can declare a base class MyComponent : Control. That component overrides MousClick event and raise a special event notifying about a fact. Every control in your app derive from that control, so every control will notify about click happened on it. It's enough to subcribe
to thier events and process them as requested.
Just a couple of ideas...
You'd have to wire them all up to the same event handler. This can be done in the properties window for the controls in question. You could also write your own function to traverse the control tree and tie the function to each of their event handlers.
You can recursively traverse the Form.Controls collection with a foreach loop.
void attachGlobalHandler(Control aToParse, EventHandler aGlobalHandler)
{
foreach(Control lControl in aToParse.Controls)
{
attachGlobalHandler(lControl, aGlobalHandler);
lControl.Click += aGlobalHandler;
}
}
And then you call that on your form, with the name of the function you want to call:
attachGlobalHandler( Form1, myClickHandler );
And that should tie it to EVERY clickable control on the form. The sender argument of the handler should then always refer to the control that fired the event. That being said, I'd probably just attach individual event handlers, unless you need to treat multiple controls as a group.
WARNING: The code above is untested.
For the second question asked "How to determine which control has been clicked?" each control has events which may be handled in code.
The easiest way to know when a control has been clicked is to attached to the clicked event of a control which is done from the properties for the control. You may have to click the lightning bolt icon to see the events. Double-clicking beside the even will create an empty handler.
For example if you had a simple form with a single button attaching click events to the form and to the button will tell you when there is a click anywhere. In most cases the button click would be the most useful to handle.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
}
}
It's really simple!
On your click event in your Win-Form, You add
// Here is a modified version of your code:
private void Form1_Click(object sender, EventArgs e)
{
var control = Form1.ActiveControl;
}

How to Call an Event of Control that is present inside a Custom Control?

I have a Custom Cntrol that has a button inside it. Now I want to access the button click from my Application Page.
Take a look at this Post:
How to Access a Button present inside a Custom Control, from the implementing page?
You have 2 ways:
You can access the button's click event through the user control object. For eg.
MyUC.button1.click += //etc
You can create your custom event of that specific button click in the user control. For example, in your usercontrol, you have:
public delegate void OnButtonClick(object sender, EventArgs e);
public event OnButtonClick Button1Click;
button1_click(object sender, EventArgs e)
{
if(Button1Click != null)
Button1Click(this, e);
}
Then you watch for that event on your user control:
MyUC.Button1Click += //etc.

Categories