2015-02-23 66 views
3

我有以下视图模型NotifyPropertyChanged上依赖特性

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

在我看来,我想启用/禁用取决于密码的文本框是否具有价值或者不是一个按钮。

ActivateButtonEnabledPassword属性更改时未自动通知。我究竟做错了什么?我正在阅读this article,如果我理解正确,PostSharp应该能够自动处理相关属性。

+1

这应该与PS开箱即用。请,你可以在这里发布你的xaml吗?你使用什么类型的项目(WPF,Silverlight,WP等)? – 2015-02-27 11:51:34

回答

0

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

+0

不幸的是,没有奏效。 – 2015-02-24 00:33:56

0

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

的具有RaiseCanExecuteChanged()样方法ICommand接口的实现必须被用来实现所描述的行为,例如:从棱镜库

  • DelegateCommand类。
  • RelayCommand来自MVVM Light库。

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

+0

我很欣赏这种努力,但似乎很愚蠢地拉入棱镜,走出我的方式去寻找那些应该可以用我目前已有的工具开箱即用的东西。 – 2015-02-24 16:01:20

+0

@TheMuffinMan,当然,棱镜库仅用于例子。可以使用另一个合适的'ICommand'接口实现(其他库)或在当前解决方案(项目)中创建。答案已更新。 – 2015-02-24 18:22:09

0

在视图中,您使用的是什么控件?密码箱?可能的是,财产密码永远不会更新。

出于安全原因,Passwordbox.Password不是依赖项属性,而是不支持绑定。你有一个解释,并在可能的解决方案:

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

如果控制不是passwordbox,你可以写我们的看法?

+0

我正在使用passwordchanged事件的事件处理程序,然后在处理程序中手动设置'Password',但我也尝试使用常规文本框而没有更改的处理程序,它仍然不起作用。 – 2015-02-24 15:54:44

+0

视图很简单。 'Textbox text =“{Binding Path = Password}”''Button IsEnabled =“{Binding Path = ActivateEnabled}”' – 2015-02-24 16:04:17