依赖属性上的NotifyPropertyChanged

时间:2015-02-23 23:38:34

标签: c# wpf mvvm postsharp

我有以下视图模型

[NotifyPropertyChanged]
public class ActivateViewModel
{
    public string Password { get; set; }
    public bool ActivateButtonEnabled { get { return !string.IsNullOrEmpty(Password); } }
    ...
}

在我看来,我尝试根据密码文本框是否有值来启用/禁用按钮。

ActivateButtonEnabled属性更改时,

Password不会自动得到通知。我究竟做错了什么?我正在阅读this article,如果我理解正确,PostSharp应该能够自动处理依赖属性。

3 个答案:

答案 0 :(得分:0)

我认为你需要以'this.Password'的形式访问密码,因为PostSharp在所有相关属性之前都需要'this'访问器。

答案 1 :(得分:0)

请考虑使用ICommand界面。接口包含ICommand.CanExecute Method,用于确定命令是否可以在当前状态下执行。 ICommand接口的实例可以绑定到Command实例的Button属性。如果无法执行该命令,该按钮将自动禁用。

必须使用具有ICommand类似方法的RaiseCanExecuteChanged()接口实现来实现所描述的行为,例如:

    来自Prism图书馆的
  • DelegateCommand课程。
  • 来自MVVM Light库的
  • RelayCommand

使用Prism库中的ViewModel类实现DelegateCommand

[NotifyPropertyChanged]
public class ActivateViewModel
{
    private readonly DelegateCommand activateCommand;
    private string password;

    public ActivateViewModel()
    {
        activateCommand = new DelegateCommand(Activate, () => !string.IsNullOrEmpty(Password));
    }

    public string Password
    {
        get { return password; }
        set
        {
            password = value;
            activateCommand.RaiseCanExecuteChanged(); // To re-evaluate CanExecute.
        }
    }

    public ICommand ActivateCommand
    {
        get { return activateCommand; }
    }

    private void Activate()
    {
        // ...
    }
}

XAML的代码:

<Button Content="Activate"
        Command="{Binding ActivateCommand}" />

没有找到有关PostSharp ICommand - 界面支持的文档,但问题是:INotifyPropertyChanged working with ICommand?, PostSharp Support

答案 2 :(得分:0)

在视图中,您使用的是什么控件?一个PasswordBox?可以认为属性密码永远不会更新。

出于安全原因,Passwordbox.Password不是依赖项属性,因此不支持绑定。您有以下解释和可能的解决方案:

http://www.wpftutorial.net/PasswordBox.html

如果控件不是密码框,您可以将视图写入我们吗?

相关问题