问题描述
我是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));
}
}
解决方法
如果从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的信息here。
编辑
如果只想启用按钮,则在设置了特定文本后,可以添加如下条件:
public string Name
{
get
{
return name;
}
set
{
this.RaiseAndSetIfChanged(ref name,value);
if (Name == Greeting)
{
Enable = true;
}
else
{
Enable = false;
}
}
}