【问题标题】:Guard Clause Not Firing保护条款不触发
【发布时间】:2011-10-06 21:43:27
【问题描述】:

所以我一直在尝试让保护条款与 Caliburn.Micro 和绑定的文本框一起使用。

观点:

<TextBox x:Name="UserAccount_DisplayName" Margin="-10,-5,-10,8"/>

<phone:PhoneApplicationPage.ApplicationBar>
  <shell:ApplicationBar IsVisible="True" IsMenuEnabled="False">
     <shell:ApplicationBar.Buttons>
        <cal:AppBarButton IconUri="\Resources\Iconography\appbar.check.rest.png"
                          Text="Save"
                          Message="SaveAndNavigateToAddAccountView" />
     </shell:ApplicationBar.Buttons>
  </shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>

视图模型:

public class EditAccountNameViewModel: PropertyChangedBase

    public Account UserAccount
    {
        get
        {
            return account;
        }
        set
        {
            account = value;
            NotifyOfPropertyChange(() => UserAccount);
            NotifyOfPropertyChange(() => CanSaveAndNavigateToAddAccountView);
        }
    }

    public bool CanSaveAndNavigateToAddAccountView
    {
        get
        {
            if (string.IsNullOrEmpty(UserAccount.DisplayName) == true)
            {
                return false;
            }

            return true;
        }   
    }

    public void SaveAndNavigateToAddAccountView()
    {
        CommitAccountToStorage();
        navigationService.UriFor<AddAccountViewModel>().Navigate();
    }

由于某种原因,在我开始在文本框中输入后,保护子句没有触发,这是我认为应该发生的。有什么想法吗?

【问题讨论】:

    标签: c# windows-phone-7 mvvm caliburn.micro guard-clause


    【解决方案1】:

    当您在文本框中键入内容然后选择另一个元素时(使文本框失去焦点),是否会触发保护子句?如果是这样,请尝试模拟绑定的 UpdateSourceTrigger=PropertyChanged 设置。请参阅"UpdateSourceTrigger=PropertyChanged" equivalent for a Windows Phone 7 TextBox 的回复以了解如何模拟此行为。

    编辑:我明白了,您正在(按照惯例)绑定到 UserAccount 的“DisplayName”属性。这意味着,当您在文本框中键入内容时,不会调用 EditAccountNameViewModel.UserAccount 属性的设置器。相反,将调用 UserAccount.DisplayName 上的设置器。我建议你做的是在你的 ViewModel 中创建另一个属性,比如 UserAccountDisplayName,看起来像这样,然后绑定到它:

    public string UserAccountDisplayName
    {
       get { return UserAccount.DisplayName; }
       set 
       {
          UserAccount.DisplayName = value;
          NotifyOfPropertyChange(() => UserAccountDisplayName);
          NotifyOfPropertyChange(() => CanSaveAndNavigateToAddAccountView);
       }
    }
    

    这个 + 模拟 PropertyChanged 触发器应该可以工作。

    【讨论】:

    • 不,它第一次触发(当视图实例化时),然后在我输入时它什么都不做,而不是当我失去焦点时:(
    • 我添加了另一个建议
    • 效果很好,我不需要添加属性更改触发器。干杯!
    猜你喜欢
    • 2017-03-19
    • 2012-11-25
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    相关资源
    最近更新 更多