【问题标题】:How to get the "{Binding}" instance from within the behavior?如何从行为中获取“{Binding}”实例?
【发布时间】:2018-10-12 19:40:13
【问题描述】:

我创建了一个行为来在出现错误时验证控件。行为需要知道控件的Binding(视图模型)源,因为ViewModel 实现IDataErrorInfo,并且行为需要订阅the ErrorChanged 事件以在发生错误时做出适当的操作。

为此,我添加了一个依赖属性 ValidationSource,它将始终设置为 "{Binding}"

<TextBox Text="{Binding LastName, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}">
  <i:Interaction.Behaviors>
    <b:MyValidateOnErrorBehavior PropertyName="LastName" ValidationSource="{Binding}" />
  </i:Interaction.Behaviors>
</TextBox>

这个解决方案对我有用,但我不想一直输入ValidationSource="{Binding}"

有没有一种方法可以从行为中获取"{Binding}" 实例,而无需在依赖属性中设置它?

【问题讨论】:

    标签: xaml uwp dependency-properties behavior


    【解决方案1】:

    在 Behavior 的代码中,您可以获取 AssociatedObject.DataContext 来获取 - 这将是您的 ViewModel。

    【讨论】:

    • 当您没有将任何内容绑定到 VM 时,情况并非如此。如果您查看我的示例,则有两个属性,即 PropertyName 和 ValidationSource。一旦我删除了validationSource,就没有更多的属性绑定到VM,因为PropertyName 是一个文字字符串“LastName”。如果是这样的话,当你查看 AssociatedObject.DataContext 时,它是 null。
    • AssociatedObject 指的是 TextBox,无论您的 ValidationSource 属性的值如何,这个都有一个 DataContext,不是吗?
    猜你喜欢
    • 1970-01-01
    • 2015-01-08
    • 2010-10-12
    • 2019-07-08
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2013-08-22
    • 2010-09-19
    相关资源
    最近更新 更多