Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Button Content and Text Based On Previous Click

Tags:

c#

.net

windows

wpf

I want to change the button content depending on the previous content click. For example, if its Add then it should change to Save, and if it is Save then it should change back to Add.

I know how to change the content of a button. but how can one read the content to make a change?

like image 381
Hasan Zubairi Avatar asked Apr 04 '12 03:04

Hasan Zubairi


People also ask

How do you change the button text in typescript?

You can use ngOnInit on your class like this and change the innerText value afterwards to the required string value. Save this answer.


2 Answers

Store the value of last click in the tag property of that button and check for its value on click.

Tag Description

Gets or sets an arbitrary object value that can be used to store custom information about this element.

MSDN Link

OR

void MyButton_OnClick(object sender, RoutedEventArgs e)
{
    if(mybutton.Content.ToString() == "Add")
    {
        \\ Lines for add
        mybutton.Content = "Save";
    }
    else
    {
        \\ Lines for Save
        mybutton.Content = "Add";    
    }
}
like image 92
Nikhil Agrawal Avatar answered Nov 15 '22 04:11

Nikhil Agrawal


If you are using MVVM, bind the content to a value and bind the command to function.

<Button Content="{Binding ButtonText}" Command="{Binding ButtonClickCommand}"/>

Of course, you then have String ButtonText and ButtonClickCommand as properties in your ViewModel.

private string _ButtonText;
public string ButtonText
{
    get { return _ButtonText ?? (_ButtonText = "Add"); }
    set
    { 
        _ButtonText = value;
        NotifyPropertyChanged("ButtonText"); 
    }
}

private ICommand _ButtonClickCommand;
public ICommand ButtonClickCommand
{
    get { return _ButtonClickCommand ?? (_ButtonClickCommand = _AddCommand); }
    set
    {
        _ButtonClickCommand = value;
        NotifyPropertyChanged("ButtonClickCommand");
    }
} 

private ICommand _AddCommand = new RelayCommand(f => Add());
private ICommand _SaveCommand = new RelayCommand(f => Save());

private void Add()
{
    // Add your stuff here

    // Now switch the button   
    ButtonText = "Save";
    ButtonClickCommand = SaveCommand;
}

private void Save()
{
    // Save your stuff here

    // Now switch the button   
    ButtonText = "Add";
    ButtonClickCommand = AddCommand;
}

Then you can have the ButtonClickCommand change the properties and binding takes care of everything.

like image 15
Rhyous Avatar answered Nov 15 '22 06:11

Rhyous