vrnithinkumar
vrnithinkumar

Reputation: 1363

In WPF how to Make Button enabled/disabled depending on the input of different TextBox Text property?

How to Make Button enabled/disabled depending on the input of different TextBox Text property using wpf binding ?

Related question: Make Button enabled/disabled depending on the TextBox Text property in WPF?

I saw this question similar but this enabling/disabling depends on one TextBox.

Is there any way to bind a button enabling/disabling with more than one TextBox Text properties ? Specifically, need to disable/enable the button based on a ItemsControl containing a list of TextBox ?

Upvotes: 0

Views: 2809

Answers (2)

Martin
Martin

Reputation: 5623

I would like to approach this problem in an MVVM way.

Usually when working with a Button you set the Command property in XAML...

<Button Command="{Binding MyCommand}" Content="Click Me"/>

and in your view model you have a ICommand associated with it.

public class MyViewModel
{
    private ICommand _myCommand;
    public ICommand MyCommand
    {
        get
        {
            if (_myCommand== null)
            {
                _myCommand = new RelayCommand(
                    p => this.CanMyCommandExecute(),
                    p => this.MyCommandExecute()
            }
            return _myCommand;
        }
    }
}

You see that you create the ICommand instance in your view model and write the code for CanExecute method there too. The CanExecute method returns a bool which tells whether the command is able to execute under the current conditions.

WPF will automatically disable or enable the button connected with the ICommand depending on whether the CanExcute method returns true or false.

In the "CanExecute" method you can write code which takes the values of several other bound properties of your view model into account and then returns true of false.

So let's say you have 3 TextBox controls and 3 bound string values in your view model. In the CanExecute method you check the values of these 3 strings properties and return true or false. The button will then be enabled or disabled accordingly.

Upvotes: 1

Nikita Shrivastava
Nikita Shrivastava

Reputation: 3018

You can follow these simple steps, I do not wanted to write the whole code by myself but feel free to ask in case you find it difficult:
1. Based on the linked question, Set the ElementName as the ItemsControlName.
2. Create a converter that takes the control as value. In the convert() , check the conditions on the Items of the ItemsControl(value) & return disabled/Enabled(False/true) from the convert().
3.Create an instance of the converter with a key inside Windows.Resources.
4. Add the converter to the IsEnabled="{ElementName=ItemsControlName,Path={Binding},Converter={StaticResource convKey}}".
You might get some syntactical errors,please correct them & give it a try.

Upvotes: 1

Related Questions