Question

What is the simplest way in WPF to enable a Button when the user types something into a TextBox?

Was it helpful?

Solution

Use the Simple Command

<TextBox Text={Binding Path=TitleText}/>

<Button Command="{Binding Path=ClearTextCommand}" Content="Clear Text"/>

Here is the sample code in the View Model

public class MyViewModel : INotifyPropertyChanged
{
    public ICommand ClearTextCommand { get; private set; }

    private string _titleText; 
    public string TitleText
    {
        get { return _titleText; }
        set
        {
            if (value == _titleText)
                return;

            _titleText = value;
            this.OnPropertyChanged("TitleText");
        }
    }   

    public MyViewModel()
    {
        ClearTextCommand = new SimpleCommand
            {
                ExecuteDelegate = x => TitleText="",
                CanExecuteDelegate = x => TitleText.Length > 0
            };  
    }            

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = this.PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }     
}

For more information see Marlon Grechs SimpleCommand

Also check out the MVVM Project Template/Toolkit from http://blogs.msdn.com/llobo/archive/2009/05/01/download-m-v-vm-project-template-toolkit.aspx. It uses the DelegateCommand for commanding and it should be a great starting template for any project.

OTHER TIPS

Why is everyone making things so complicated!

    <TextBox x:Name="TB"/>
    <Button IsEnabled="{Binding ElementName=TB,Path=Text.Length}">Test</Button>

Nothing else needed......

IF you were not using Commands, another alternative is using a Converter.

For example, using a generic Int to Bool converter:

  [ValueConversion(typeof(int), typeof(bool))]
  public class IntToBoolConverter : IValueConverter
  {
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
      try
      {
        return (System.Convert.ToInt32(value) > 0);
      }
      catch (InvalidCastException)
      {
        return DependencyProperty.UnsetValue;
      }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
      return System.Convert.ToBoolean(value) ? 1 : 0;
    }

    #endregion
  }

Then on the buttons IsEnabled property:

<Button IsEnabled={Binding ElementName=TextBoxName, Path=Text.Length, Converter={StaticResource IntToBoolConverter}}/>

HTH,

Dennis

Use a trigger!

<TextBox x:Name="txt_Titel />
<Button Content="Transfer" d:IsLocked="True">
  <Button.Style>
    <Style>
      <Style.Triggers>
        <DataTrigger Binding="{Binding ElementName=txt_Titel, Path=Text}" Value="">
         <Setter Property="Button.IsEnabled" Value="false"/>
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </Button.Style>
</Button>

The key on this is on the binding itself..

Add UpdateSourceTrigger = PropertyChanged

this is the most simple solution

Add a callback to the TextBox that fires on every stroke. Test for emptiness in such callback and enable/disable the button.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top