Cómo habilitar un botón cuando un usuario escribe en un cuadro de texto
Pregunta
¿Cuál es la forma más sencilla en WPF de habilitar un Button
cuando el usuario escribe algo en un TextBox
?
Solución
Usa el comando simple
<TextBox Text={Binding Path=TitleText}/>
<Button Command="{Binding Path=ClearTextCommand}" Content="Clear Text"/>
Aquí está el código de ejemplo en el modelo de vista
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));
}
}
Para obtener más información, consulte Marlon Grechs SimpleCommand
También puedes ver la plantilla / kit de herramientas del proyecto MVVM en http://blogs.msdn.com/llobo/archive/2009/05/01/download-mv-vm-project-template-toolkit.aspx . Utiliza el comando DelegateCommand para mandar y debe ser una excelente plantilla de inicio para cualquier proyecto.
Otros consejos
¡Por qué todos hacen las cosas tan complicadas!
<TextBox x:Name="TB"/>
<Button IsEnabled="{Binding ElementName=TB,Path=Text.Length}">Test</Button>
Nada más se necesita ......
Si no estaba usando los Comandos, otra alternativa es usar un Convertidor.
Por ejemplo, usando un convertidor genérico de 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
}
Luego, en los botones de la propiedad IsEnabled:
<Button IsEnabled={Binding ElementName=TextBoxName, Path=Text.Length, Converter={StaticResource IntToBoolConverter}}/>
HTH,
Dennis
Usa un disparador!
<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 clave de esto está en el enlace en sí ..
Agregar UpdateSourceTrigger = PropertyChanged
esta es la solución más simple
Agregue una devolución de llamada al TextBox que se activa en cada golpe. Pruebe el vacío en dicha devolución de llamada y habilite / deshabilite el botón.