如何根据文本框值在 AvaloniaUI 中启用按钮

How to make button enabled in AvaloniaUI depending on Textbox value

我是 Avalonia 的新手,所以我的代码应该很基础。我有 1 个 window,里面有 1 个面板,即:

<StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center" Width="300">
<TextBlock Text="{Binding Greeting}" />

<TextBox Text="{Binding Name}"/>
<Button Content="Say HI" Click="OnButtonClicked" IsEnabled="{Binding Enable}"/>

该面板有 TextBlock、TextBox 和按钮。默认情况下不启用该按钮。 我的问题是,当 textBox 的值发生变化时,如何启用它。这是我的模型 class,其中已经包含了一些基本逻辑:

class HelloViewModel : INotifyPropertyChanged
{
    private string greeting = "";
    private string name = "";
    public bool Enable = false;

    public string Greeting
    {
        get => greeting;

        set
        {
            if (value != greeting)
            {
                greeting = value;
                OnPropertyChanged();
                Enable = true;
            }
        }
    }

    public string Name
    {
        get => name;
        set
        {
            if(value != name)
            {
                name = value;
                OnPropertyChanged();
                Enable = true;
            }
        }
    }

   

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

如果您从 Avalonia 模板创建一个新的 MVVM 项目,您将获得 ViewModelBase class。我建议使用它。

ViewModelBase.cs

public class ViewModelBase : ReactiveObject
{
}

MainWindowViewModel.cs

public class MainWindowViewModel : ViewModelBase
{
    public string Greeting {
        get => "Welcome to Avalonia.";
    }

    private bool enable = false;
    public bool Enable
    {
        get => enable;
        set => this.RaiseAndSetIfChanged(ref enable, value);
    }

    private string name = string.Empty;
    public string Name
    {
        get
        {
            return name;
        }
        set
        {
            this.RaiseAndSetIfChanged(ref name, value);
            Enable = true;
        }
    }
}

为了确保,MainWindow.xaml

  <Design.DataContext>
      <vm:MainWindowViewModel/>
  </Design.DataContext>

<StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center" Width="300">
  <TextBlock Text="{Binding Greeting}" />

  <TextBox Text="{Binding Name}"/>
  <Button Content="Say HI" Click="OnButtonClicked" IsEnabled="{Binding Enable}"/>
</StackPanel>

其中 vmxmlns:vm="clr-namespace:<YourNamespaceContainingTheViewModel>;assembly=<YourProject>"

可以找到其他信息以及如何从 CodeBehind 设置 ViewModel here

编辑

如果您只想启用按钮,当设置特定文本时,您可以添加这样的条件:

public string Name
{
  get
    {
        return name;
    }
    set
    {
        this.RaiseAndSetIfChanged(ref name, value);
        if (Name == Greeting)
        {
            Enable = true;
        }
        else
        {
            Enable = false;
        }
    }
}