Change Button Content and Text Based On Previous Click
Asked Answered
L

6

12

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?

Lamanna answered 4/4, 2012 at 3:10 Comment(0)
O
13

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";    
    }
}
Oscitant answered 4/4, 2012 at 3:14 Comment(1)
This is not how you show do this in WPF. Maybe in WinForms.Labionasal
P
16

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.

Passivism answered 4/4, 2012 at 3:35 Comment(3)
How do you get NotifyPropertyChanged() to be accessible? What do you have to implement?Tully
When I answered this, I was likely using a ViewModelBase with NotifyPropertyChanged already implemented. See Step 2 of this article: rhyous.com/2010/12/29/…Passivism
Id recommend you show that in your answer, eg what namespaces you are using (really helpful to show using statements) and what you are extending.Tully
O
13

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";    
    }
}
Oscitant answered 4/4, 2012 at 3:14 Comment(1)
This is not how you show do this in WPF. Maybe in WinForms.Labionasal
T
7

I agree with Surfens answer that the question here is not a perfect example for a ToggleButton because "Save" and "Add" a really different operations which should each have the own "ICommand" set on the respective button.

But here is some style that will change the content depending on the IsChecked value of the ToggleButton.

The content will be "ValueForUnToggledState" if the button is not checked and change to "ValueForToggledState" when checked.

<ToggleButton>
    <ToggleButton.Style>
        <Style TargetType="{x:Type ToggleButton}">
            <Setter Property="Content" Value="ValueForUnToggledState" />
            <Style.Triggers>
                <Trigger Property="IsChecked" Value="True">
                    <Setter Property="Content" Value="ValueForToggledState" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ToggleButton.Style>
</ToggleButton>

This is more WPF like than some of the other answers.

Talbert answered 9/6, 2017 at 7:27 Comment(0)
M
4

An alternate design could be if one created 2 buttons such as AddButton and SaveButton, then one could show or hide them respectively (using Visibility property).

Why?

Because it is a Matter of Separation of Concerns. For example, in the click handler you wouldn't need to check the mode you're in, because you'll have separate handlers. You will also want the buttons to have different icons, different Tooltips, etc.

Munford answered 4/4, 2012 at 3:14 Comment(0)
M
3

You can also use a ToggleButton with EventTriggers to execute the different methods for Checked and Unchecked states.

<ToggleButton x:Name="ToggleButton" Content="Add"
              Style="{StaticResource ToggleStyle}"
              IsThreeState="False">
     <i:Interaction.Triggers>
      <i:EventTrigger EventName="Checked">
      <ei:CallMethodAction MethodName="Save" TargetObject="{Binding}" />
     </i:EventTrigger>
     <i:EventTrigger EventName="Unchecked">
       <ei:CallMethodAction MethodName="Add" TargetObject="{Binding}" />
     </i:EventTrigger>
 </i:Interaction.Triggers>
 </ToggleButton>

You can also use a style to modify the ToggleButton template and change the text for the checked state. To do this, get a copy of the ToggleButton style and in the Checked VisualState add this to the story board:

<ObjectAnimationUsingKeyFrames Storyboard.TargetName="contentPresenter" Storyboard.TargetProperty="(UIElement.Content)">
 <DiscreteObjectKeyFrame KeyTime="0">
    <DiscreteObjectKeyFrame.Value>
         Save
    </DiscreteObjectKeyFrame.Value>
   </DiscreteObjectKeyFrame>
 </ObjectAnimationUsingKeyFrames>

If you'd rather not go down that route then you could add this to your Checked Triggers:

<ei:ChangePropertyAction PropertyName="ButtonText" Value="Save"/>

To use these approaches you will need a reference to the Microsoft.Expression.Interactions and System.Windows.Interactivity binaries from C:\Program Files (x86)\Microsoft SDKs\Expression\Blend.NETFramework\v4.5\Libraries.

Monitory answered 7/8, 2014 at 15:8 Comment(1)
They are blend namespace aliases in the xaml for Microsoft.Expression.Interaction (ei) and System.Windows.InteractivityMonitory
D
0

You can get access to pressed button by using object sender and by casting this object to Button type. When object is casted to Button you are able to check or change Content field value.

Sample code:

private void Button_OnClick(object sender, RoutedEventArgs e)
{    
    if (((Button)sender).Content + "" == "Old button name") // get Content value            
        ((Button)sender).Content = "New button name"; // set Content value
}
Dinorahdinosaur answered 27/8, 2024 at 16:24 Comment(1)
please add explanation to your code how it solves the issueAmling

© 2022 - 2025 — McMap. All rights reserved.