Change content property from dynamically created button - c#

I have dynamically created button in C# using XAML.
The XAML:
<Grid Name="mainGrid" Grid.Row="1"></Grid>
and I had created button with this code in C#:
Button dugme = new Button();
dugme.Content = "tap me";
dugme.Tapped += dugme_Tapped;
mainGrid.Children.Add(dugme);
How can I now change button Content (text) from "tap me" to "tapped ok" in this event.
void dugme_Tapped(object sender, TappedRoutedEventArgs e)
{
//should I use binding?
}

Just as you set the Content property to "tap me" when you create the button, so too can you set it in the event handler:
void dugme_Tapped(object sender, TappedRoutedEventArgs e)
{
((Button)sender).Content = "tapped ok";
}
That said, you ask in a code comment "should I use binding?" and, since this is WPF, the default answer is "yes". But how exactly you would do that here is difficult to say, given the lack of context. It's not clear why you are adding the Button instance programmatically (doing which is itself non-idiomatic in WPF).
If guess if you feel you have a very good reason to eschew XAML-based initialization and binding for the creating of the Button instance, you may as well continue that approach for setting the Content property. In that case, the above example should work for you.
If you would like a more XAML-centric approach, you probably should ask a different question, starting with explaining clearly your scenario and asking how to initialize the button in a more WPF-like manner, as well as how to maintain the state of the Content property of that button.

As to whether you should use binding, this being XAML, almost certainly, it makes your code a lot easier to maintain by keeping the view and model separate, though you might have a good reason.
As to changing the text, you can just set the content property of your button in the event handler.
By default, the object that fired the event is passed as the 'sender' parameter of you function, so all you need is this:
void dugme_Tapped(object sender, TappedRoutedEventArgs e)
{
(sender as Button).Content = "tapped ok";
}
As your event handler.

Related

How to know which button has been pressed when you have a generic buttonclicked event?

I havent been able to think of the right wording for this question so apologies if its confusing.
I'm writing a program that will give a user an ability to send hex commands over serial for a number of custom object types.
I have 8 buttons on the XAML menu page each one representing each object and I have my C# buttonclick event that does its thing when one of the buttons is clicked but I need to be able to know which button is clicked without having to write a method of each individual button.
This is due to the user having the ability to create additional buttons dynamically.
How can I tell the buttonclicked event which of the buttons (1-8 etc) has been pressed?
<Button Content="Button!" Click="OnButtonClick" Command="{Binding WhateverCommand}" />
private void OnButtonClick(object sender, RoutedEventArgs e)
{
Button b = e.Source as Button; //Here you can get which button is clicked
}
The answer from David is one possible solution. But I'm not sure what you are doing then? What should happen then? Is it depends on Button Name (Content), or something else?
Without knowing your exactly problem I would nevertheless prefer the MVVM pattern based solution.
I would do an ObservableCollection of SomeActionViewModel which have a ICommand property and bind that property in XAML-Template Command={Binding MyCommand}. I whould bind the ObservableCollection to some ItemsControl and template it to display buttons
Here is a similar problem with MVVM example
https://social.msdn.microsoft.com/Forums/en-US/2cf2757c-e2a1-4b93-b130-6d900b1359ea/how-to-bind-a-different-command-to-each-dynamic-button-in-c?forum=wpf

Xamarin forms xaml button click handler not fired c#

I has rey use VS 2015 with xamarin forms to create a cross platform project. I add the xaml page which contain a text box and button. In the code behind, I has code as below
public Inno()
{
InitializeComponent();
btntest.Clicked += Btntest_Clicked;
}
Private void Btntest_Clicked(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(Name.Text))
{
return;
}
}
When I run the android simulator to test the page, it fire the constructor. But when I clicke the button, it not fire the click event. Anything goes wrong? Please help. Thanks
Theres a few things you can try:
hook up the event handler in the xaml, see if that works - because you are subscribing to the event in the constructor this shouldn't make a difference functionality wise.
Edit: to do this, in your xaml:
<Button Clicked="buttonClicked" />
and Press tab when intellisense prompts you to create a new handler.
as #hankide said - set a breakpoint and make sure it isn't actually entering it and that the problem isn't the code inside the event handler.
You need to make sure that your btntest object has been properly mapped to the button on the XAML side of things. By default, XAML objects don't have "names" as you may be accustomed to in WinForms or WebForms and need to have a name property assigned to them. For me, I typically have my buttons marked up as:
<Button x:Name=btntest Text="Click Me></Button>
Then in the code behind I have to find the button by name in order to wire up the event:
var testButton = this.FindByName<Button>("btntest");
testButton.Clicked += Btntest_Clicked;
From there everything works as expected.
Try this:
btntest.Clicked += new EventHandler(Btntest_Clicked);
Thanks everyone for the answer...not sure why I close the solution and re-open it, it work fine.

How to hide control when click outside it?

I have a WindowForm and some controls on it.
My point is that when I click button "?" on top-right of the datagridview, it will show a picture box and when I click outside the pictureBox, it must invisible.
My MainForm
MyPictureBox
I have searched some topics on this site, but some dont work, some work partly. Like
this.
I also tried:
void pictureBox1_LostFocus(object sender, EventArgs e)
{
if (pictureBox1.Visible)
pictureBox1.Visible = false;
}
But when I click on button2, button3, ... The pictureBox wasn't invisible.
Any solution will be highly appreciated.
I think your pictureBox1 isn't losing focus, cause it never actually GOT focused. Set it to be focused after making it visible.
Oh, I have encountered this before...
I was making a Label that you could double click and it would allow you to edit the Label.Text, like a TextBox. However, I was having problems hooking into the events to know when the user had clicked off the Control and wished to stop editing. I tried Control.LostFocus, and Control.Leave, but nothing. I even got frustrated/desperate and tried some silly ones like Control.Invalidated.
What I ended up having to do was subscribe to the Click event of the Form/Container/Control behind it.
However, putting the responsibility of wiring up this event into the Form that wants to use it is poor design. What you can do, however is to make the constructor to Control class require a reference to the owner/parent/container as a parameter. That way, the requirements are not hidden, they must be satisfied before you can get a object instance, and the control can wired up to the Form.Click within itself, where that logic belongs.
private Form owner;
public EditLabel(Form Owner)
{
this.owner = Owner;
owner.Click += EndEditing;
}
Add this method in designer.cs:
pictureBoxEvent this.MouseLeave += new EventHandler(pictureBox_MouseLeave);
Add this code in cs file:
private void pictureBox_MouseLeave(object sender, EventArgs e)
{
pictureBox1.Visible = false;
}

C# multiple button with similar behavior

I am new to C# and I am following this C# tutorial at the moment. In this tutorial I came across the exercise to develop a calculator.
A C# .Net Calculator - Design Stage
In the solution given in the exercise, each digit button was given a btn*_click method which can be generalized pretty easily.
(source: homeandlearn.co.uk)
How can we write the code, so that we can generalize these 10 functions? I though it can be done by modifying initializeComponent(), but comment about it says it should not be modified using code editor.
How can this problem be tackled.
You can tie all buttons to the same click event handler, and use sender to get the text:
private void btnAnyButton_Click(object sender, EventArgs e)
{
Button theButton = sender as Button;
txtDisplay.Text += theButton.Text;
}
The tutorial you posted is using the visual editor in visual studios. By default the designer will generate code with the convention {controlname}_{eventname} you can explicitly assign a different event name in the properties window, and all the buttons could share the same event method.
And then it looks like you could refactor this like:
private void btn_click(object sender, EventArgs e)
{
Button btn = sender as Button;
if(btn != null)
txtDisplay.Text += btn.Text;
}
I hope that helps.
You could generate these buttons dynamically from the code and assign them some value in the tag attribute. From there, you can hook them all up to the same event handler (we're talking about the number buttons, as in 0,1,2,3,4...). In the onClick event handler you would get the tag value of the caller and do what you have to do.
Pseudocode:
void onClick(Button caller){
int btnNb = (int) caller.Tag;
//do what you have to do
}
The tag attribute is not necessary but I find it cleaner than getting the button text and converting to an int.

How do I register event handlers for a web user control in my code behind?

I'm having a problem setting up an event on a form. Here's the setup:
I was given a page with two controls, two different versions of a form for the end-user to fill out- standard and advanced. The two forms have different code and javascript, so the original dev put them in separate web user controls. Aside from the controls is a LinkButton that switches to Advanced mode.
<uc1:Standard runat="server" ID="StandardForm" />
<uc1:Advanced runat="server" ID="AdvancedForm" />
<asp:LinkButton runat="server" ID="lnkAdvanced" Text="Go To Advanced" OnClick="lnkAdvanced_Click" />
lnkAdvanced_Click just takes all the info currently entered to the advanced and flips the Visible.
My problem is that one of the bosses wants the 'Go to Advanced' button inside the standard form, but the .Visible code is on the page. So I thought it could be done using an event, but it doesn't seem to be working.
I tried to set up the event like this:
public event EventHandler AdvanceClick;
protected void lnkAdvanced_Click(object sender, EventArgs e) {
AdvanceClick(sender, e);
}
And when that didn't work, I tried to set up a delegate:
public delegate void AdvancedEventHandler(object sender, EventArgs e);
public event AdvancedEventHandler AdvanceClick;
When I moved the button to the standard form, I expected to be able to type something like:
StandardForm.AdvanceClick += new AdvancedEventHandler(GoToAdvanced);
But it doesn't seem to recognize any events within the control! I get an error: "Standard does not contain a definition for 'AdvanceClick' and no extension method 'AdvanceClick accepting a first argument of type 'Standard' could be found" It finds the other properties just fine, am I going about this the wrong way?
// in your Standard user control
public event EventHandler AdvancedClick;
private void lbtnAdvanced_Click(object sender, EventArgs e)
{
OnAdvancedClick(e);
}
protected void OnAdvancedClick(EventArgs e)
{
if (AdvancedClick != null)
AdvancedClick(this, e);
}
// on your page
StandardForm.AdvancedClick += new EventHandler(StandardForm_AdvancedClick);
private void StandardForm_AdvancedClick(object sender, EventArgs e)
{
// toggle logic here
}
If the standard form has the "Switch to advanced" button. Then, clearly, it has to know about the Advanced form and thus they seem to be pretty tightly coupled. If this is the case, it seems to me that you might as well just have the advanced form as a child of the standard form then... or better yet, merge them into one control.
If you don't like these options you might want to create a third controls which hosts the button and the two forms, along with the logic to move data between them and toggle their visibility.
I personally recommend the single control option. Having tighly coupled controls usually just leads to confusion down the road. You could loosen up the dependency in various ways, but think hard about it before you do so.
In the legacy project I currently work on we have a bunch of examples such as serach forms and search results being split up into multiple controls, but then in the end needing each others instances to function properly. As I said earlier, I wont reccomend this path.
You shouldn't need the delegate because you've created a standard event.
Try in your form load or thereabouts:
StandardForm.AdvanceClick += new EventHandler(GoToAdvanced);
Then somewhere on the page that hosts the 2 user controls
protected void GoToAdvanced(object sender, EventArgs e)
{
//Code that was previously in lnkAdvanced_Click on page.
}
Edit:
It does sound like the setup is wrong.
Can you post the markup for the Host page (at this point we are assuming it is simply the 2 user controls).
Then we are also assuming that the AdvanceClick event is declared in the Standard UC but the error message would indicate that it doesn't.. and the lnkAdvanced_Click method is in the Standard UC?
Then we are assuming the code that is attempting to attach to the custom event is declared in the Host page.
If you could confirm or deny the assumptions i'm sure we could get this cleared up.

Categories

Resources