依赖属性上的NotifyPropertyChanged

3
我有以下视图模型:
[NotifyPropertyChanged]
public class ActivateViewModel
{
    public string Password { get; set; }
    public bool ActivateButtonEnabled { get { return !string.IsNullOrEmpty(Password); } }
    ...
}

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

Password属性更改时,ActivateButtonEnabled没有自动通知。 我做错了什么?我正在阅读这篇文章,如果我理解正确,PostSharp应该能够自动处理依赖属性。


1
这应该可以直接在PS中使用。请问您能否在此处发布您的xaml?您正在使用哪种项目(wpf、silverlight、WP等)? - Jakub Linhart
3个回答

0

我认为你需要使用 'this.Password' 访问密码,因为 PostSharp 要求在所有相关属性之前使用 'this' 访问器。


0
在视图中,您使用了哪个控件?是 PasswordBox 吗?可能属性 password 从未更新。
Passwordbox.Password 不是依赖属性,出于安全原因,不支持绑定。您可以在以下链接中找到解释和可能的解决方案:

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

如果控件不是密码框,你能写出视图吗?


我曾经使用密码更改事件的事件处理程序,然后在处理程序中手动设置“密码”,但我也尝试使用普通文本框而没有更改处理程序,但仍然无法工作。 - The Muffin Man
视图很简单。Textbox text="{Binding Path=Password}"Button IsEnabled="{Binding Path=ActivateEnabled}" - The Muffin Man

0
请考虑使用 ICommand 接口。该接口包含 ICommand.CanExecute Method,用于确定命令是否可以在其当前状态下执行。可以将 ICommand 接口的实例绑定到 Button 实例的 Command 属性上。如果命令无法执行,则按钮将自动禁用。
要实现上述行为,必须使用具有类似于 RaiseCanExecuteChanged() 方法的 ICommand 接口实现,例如:
  • 来自 Prism 库的 DelegateCommand 类。
  • 来自 MVVM Light 库的 RelayCommand
  • 等等。
使用 Prism 库中的 DelegateCommand 类实现 ViewModel
[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是否与ICommand一起工作?,PostSharp Support


我很感谢这份努力,但是为了某件应该可以用我现有的工具轻松解决的事情而特意引入prism似乎有点儿可笑。 - The Muffin Man
@TheMuffinMan,当然,Prism库只是用作示例。可以使用其他适当的ICommand接口实现(其他库),或在当前解决方案(项目)中创建。答案已更新。 - Sergey Vyacheslavovich Brunov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接