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?
You can use ngOnInit on your class like this and change the innerText value afterwards to the required string value. Save this answer.
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";
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With