首页 文章

管理按钮的IsEnabled属性

提问于
浏览
1

我的程序中有一个xaml窗口,它有一个名为"Save"的按钮和一个 textBox . 我也有一个ViewModel用于此窗口 . 在ViewModel中,我有 textBoxstring 属性,按钮上有 IsEnabledbool 属性 . 我希望只有在 textBox 内有文本时才能启用该按钮 .

xaml:

<Button IsEnabled="{Binding SaveEnabled}" ... />
<TextBox Text="{Binding Name}" ... />

ViewModel properties:

//Property for Name
public string Name
{
    get { return _name; }
    set
    {
        _name = value;
        NotifyPropertyChange(() => Name);

        if (value == null)
        {
            _saveEnabled = false;
            NotifyPropertyChange(() => SaveEnabled);
        }
        else
        {
            _saveEnabled = true;
            NotifyPropertyChange(() => SaveEnabled);
        }
    }
}

//Prop for Save Button -- IsEnabled
public bool SaveEnabled
{
    get { return _saveEnabled; }
    set
    {
        _saveEnabled = value;
        NotifyPropertyChange(() => SaveEnabled);
    }
}

我认为我的主要问题是,我在哪里提出有关此问题的代码?正如你在上面看到的那样,我试图将它放入 Name 属性的 setter 中,但它没有成功 .

2 回答

  • 2

    你可以这样做:

    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            NotifyPropertyChanged(() => Name);
            NotifyPropertyChanged(() => SaveEnabled);
        }
    }
    
    public bool SaveEnabled
    {
        get { return !string.IsNullOrEmpty(_name); }
    }
    

    EDIT: 将此添加到您的xaml:

    <TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}">...</TextBox>
    
  • 2

    使用MVVM中使用的ICommands:

    private ICommand _commandSave;
    public ICommand CommandSave
    {
        get { return _commandSave ?? (_commandSave = new SimpleCommand<object, object>(CanSave, ExecuteSave)); }
    }
    
    private bool CanSave(object param)
    {
        return !string.IsNullOrEmpty(Name);
    }
    private void ExecuteSave(object param)
    {
    
    }
    

    然后在XAML代码中使用以下内容

    <TextBox Command="{Binding CommandSave}" ... />
    

    根据您使用的框架,命令类的工作方式不同 . 对于通用实现,我建议Relay Command .

相关问题