0

我是 Avalonia 的新手,所以我的代码应该很基本。我有 1 个窗口,其中有 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 的值发生变化时,如何启用它。这是我的 Model 类,其中已经包含一些基本逻辑:

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

1 回答 1

1

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

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>

vm在哪里xmlns:vm="clr-namespace:<YourNamespaceContainingTheViewModel>;assembly=<YourProject>"

可以在此处找到其他信息以及如何从 CodeBehind 设置 ViewModel 。

编辑

如果您只想启用按钮,则在设置特定文本时,您可以添加如下条件:

public string Name
{
  get
    {
        return name;
    }
    set
    {
        this.RaiseAndSetIfChanged(ref name, value);
        if (Name == Greeting)
        {
            Enable = true;
        }
        else
        {
            Enable = false;
        }
    }
}
于 2020-09-12T09:22:23.797 回答