【问题标题】:NotifyPropertyChanged on dependent propertiesNotifyPropertyChanged 依赖属性
【发布时间】:2015-04-25 11:31:08
【问题描述】:

我有以下视图模型

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

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

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

【问题讨论】:

  • 这应该适用于开箱即用的 PS。请问,你能在这里发布你的xaml吗?你正在使用什么样的项目(wpf、silverlight、WP 等)?

标签: c# wpf mvvm postsharp


【解决方案1】:

我认为您需要以“this.Password”的形式访问密码,因为 PostSharp 期望在所有依赖属性之前使用“this”访问器。

【讨论】:

    【解决方案2】:

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

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

    • DelegateCommand Prism 库中的类。
    • RelayCommand 来自 MVVM Light 库。

    使用 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-interface 支持的文档,但是一个问题:INotifyPropertyChanged working with ICommand?, PostSharp Support

    【讨论】:

    • 我很欣赏你的努力,但我觉得用我目前拥有的工具开箱即用地解决问题似乎很愚蠢。
    • @TheMuffinMan,当然,Prism 库仅用于示例。可以使用另一个合适的ICommand 接口实现(其他库)或在当前解决方案(项目)中创建。答案已更新。
    【解决方案3】:

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

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

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

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

    【讨论】:

    • 我使用事件处理程序处理 passwordchanged 事件,然后在处理程序中手动设置 Password,但我也尝试使用没有更改处理程序的常规文本框,但它仍然不起作用。跨度>
    • 视图很简单。 Textbox text="{Binding Path=Password}"Button IsEnabled="{Binding Path=ActivateEnabled}"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    • 1970-01-01
    • 2015-04-23
    • 2014-05-23
    相关资源
    最近更新 更多