Как включить кнопку, когда пользователь вводит текст в текстовое поле
Вопрос
Какой самый простой способ в WPF включить Button
когда пользователь вводит что-либо в TextBox
?
Решение
Используйте простую команду
<TextBox Text={Binding Path=TitleText}/>
<Button Command="{Binding Path=ClearTextCommand}" Content="Clear Text"/>
Вот пример кода в 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));
}
}
Для получения дополнительной информации см. Марлон Грекс SimpleCommand
Также ознакомьтесь с шаблоном / инструментарием проекта MVVM из http://blogs.msdn.com/llobo/archive/2009/05/01/download-mv-vm-project-template-toolkit.aspx . Он использует DelegateCommand для командования и должен быть отличным стартовым шаблоном для любого проекта.
Другие советы
Почему все делают так сложно?
<TextBox x:Name="TB"/>
<Button IsEnabled="{Binding ElementName=TB,Path=Text.Length}">Test</Button>
Больше ничего не нужно ......
ЕСЛИ вы не использовали Команды, другой альтернативой является использование конвертера.
Например, с помощью универсального преобразователя Int в 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
}
Затем на кнопках отображается свойство Enabled:
<Button IsEnabled={Binding ElementName=TextBoxName, Path=Text.Length, Converter={StaticResource IntToBoolConverter}}/>
HTH,
Деннис
Используйте триггер!
<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>
Ключ к этому находится в самой привязке..
Добавить UpdateSourceTrigger = PropertyChanged
это самое простое решение
Добавьте обратный вызов в TextBox, который срабатывает при каждом ударе. Проверьте пустоту в таком обратном вызове и включите / отключите кнопку.