文本框未更新CanExecute

时间:2019-05-24 15:24:28

标签: c# wpf mvvm

我正在使用具有“保存”按钮的MVVM应用程序,如果“标题”字段为空,我想禁用该按钮。

这是委托命令的代码:

        _clickSaveChangesCommand = new DelegateCommand<string>(
            (s) => { saveStudentRecord(); //execute },
            (s) => { return (_student.Title != null);  /*Can execute*/ }
            );

这里是绑定:

 <TextBox Name="fldTitle" Text="{Binding Path=Student.Title, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="300" Height="27" />

当我从视图模型中更新学生对象时,它会按预期工作。但是,如果我创建新记录并在文本框中键入内容,则该按钮将无法执行。在我的测试中,如果我尝试显示_student的值。标题显示为预期值。

1 个答案:

答案 0 :(得分:0)

CanExecuteChanged更改时,您需要做一些事情来引发命令的_student.Title事件。

您是否正在使用Prism的DelegateCommand?如果是这样,安迪发现了this answer。如果支持,它可能比下面的建议更好。但是see this question,就像您的情况一样,因为该属性是“孙代”属性,而不是拥有命令的类的直接属性。

如果您正在使用Prism,并且可以这样做,请尝试替换Student以查看会发生什么。在2016年,这将破坏启用更新的命令。可能还是。

所以,如果那行不通,应该这样做。

您的DelegateCommand<T>类可能具有执行该操作的方法;通常称为RaiseCanExecuteChanged()或类似名称。

最好,最好的方法是在Student的设置器中:

public Student Student
{
    get { return _student; }
    set
    {
        if (value != _student)
        {
            if (_student != null)
            {
                //  You do want to unhook this, otherwise there's a live reference 
                //  to the old _student and it won't be free to be garbage collected. 
                _student.PropertyChanged -= _student_PropertyChanged;
            }

            _student = value;

            if (_student != null)
            {
                _student.PropertyChanged += _student_PropertyChanged;
            }

            OnPropertyChanged();
        }
    }
}

private void _student_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "Title")
    {
        ClickSaveChangesCommand.RaiseCanExecuteChanged();
    }
}
相关问题