Come abilitare un pulsante quando un utente digita in una casella di testo

StackOverflow https://stackoverflow.com/questions/821121

  •  03-07-2019
  •  | 
  •  

Domanda

Qual è il modo più semplice in WPF per abilitare un Button quando l'utente digita qualcosa in un TextBox ?

È stato utile?

Soluzione

Utilizza il comando semplice

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

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

Ecco il codice di esempio nel modello di visualizzazione

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));
    }     
}

Per ulteriori informazioni, consultare Marlon Grechs SimpleCommand

Controlla anche il modello / toolkit del progetto MVVM da http://blogs.msdn.com/llobo/archive/2009/05/01/download-mv-vm-project-template-toolkit.aspx . Utilizza il comando DelegateCommand per comandare e dovrebbe essere un ottimo modello di partenza per qualsiasi progetto.

Altri suggerimenti

Perché tutti rendono le cose così complicate!

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

Nient'altro necessario ......

SE non stavi usando i comandi, un'altra alternativa è usare un convertitore.

Ad esempio, usando un generico convertitore da Int a Bool:

  [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
  }

Quindi sui pulsanti proprietà IsEnabled:

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

HTH,

Dennis

Usa un grilletto!

<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>

La chiave su questo è sul legame stesso ..

Aggiungi UpdateSourceTrigger = PropertyChanged

questa è la soluzione più semplice

Aggiungi un callback al TextBox che si attiva ad ogni tratto. Verificare la presenza di vuoto in tale richiamata e abilitare / disabilitare il pulsante.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top