当用户在 TextBox 中键入内容时,WPF中启用 Button 的最简单方法是什么?

有帮助吗?

解决方案

使用简单命令

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

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

以下是视图模型中的示例代码

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

有关详细信息,请参阅Marlon Grechs SimpleCommand

还可以从 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 to 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
  }

然后在按钮IsEnabled属性:

<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添加一个回调。测试此类回调中的空白并启用/禁用该按钮。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top