1

我的程序中有一个 xaml 窗口,它有一个名为“保存”的按钮和一个textBox. 我也有这个窗口的 ViewModel。在 ViewModel 中,我有一个, 的string属性textBox和一个按钮上的bool属性。IsEnabled我希望该按钮仅在textBox.

xml:

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

视图模型属性:

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

我认为我的主要问题是,我将有关此问题的代码放在哪里?正如您在上面看到的,我尝试将其放入属性setterName,但没有成功。

4

2 回答 2

2

你可以这样做:

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

public bool SaveEnabled
{
    get { return !string.IsNullOrEmpty(_name); }
}

编辑:将此添加到您的 xaml:

<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}">...</TextBox>
于 2013-11-07T20:36:40.377 回答
2

使用 MVVM 中使用的 ICommand:

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

于 2013-11-07T20:43:42.300 回答