사용자가 텍스트 상자에 입력 할 때 버튼을 활성화하는 방법

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

  •  03-07-2019
  •  | 
  •  

문제

WPF에서 가장 간단한 방법은 무엇입니까? Button 사용자가 무언가를 입력 할 때 TextBox?

도움이 되었습니까?

해결책

간단한 명령을 사용하십시오

<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를 참조하십시오 단순한 명령

또한 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 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를 추가하십시오

이것은 가장 간단한 솔루션입니다

모든 스트로크에서 발사되는 텍스트 상자에 콜백을 추가하십시오. 이러한 콜백에서 공허함을 테스트하고 버튼을 활성화/비활성화하십시오.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top