【问题标题】:How to know for for sure that the TargetProperty is the DataContext Property within a Markup Extension如何确定 TargetProperty 是标记扩展中的 DataContext 属性
【发布时间】:2014-12-18 19:57:52
【问题描述】:

我正在开发一个标记扩展,该扩展仅在分配给 DataContext 依赖属性时才应该工作。

这是由扩展以下列方式强制执行的:

public abstract class DataContextAssignableExtensionBase  : MarkupExtension
 {

    private void ThrowOnUnsupportedProperty(IServiceProvider serviceProvider)
    {
        var dataContextProp = TargetProperty as DependencyProperty;

        if (dataContextProp == null)
            throw new ...
        if (!(dataContextProp.Name.Equals("DataContext") || dataContextProp.Name.Equals("RuntimeDataContext")))
            throw new ...
    }
}

现在,DataContext 很可能会永远保持名为 DataContext,但仍然......

我想要一种更“安全”的方式来确保将扩展分配给 DataContext 依赖属性。

我们将不胜感激!

【问题讨论】:

    标签: wpf dependency-properties datacontext markup-extensions


    【解决方案1】:

    只需与属性定义进行参考比较:

    if (dataContextProp != FrameworkElement.DataContextProperty)
        throw ...
    

    【讨论】:

      【解决方案2】:

      除了@MikeStrobel 所说,在 .NET 4.5 和 VS2013 中,了解给定 DependencyProperty 是否是设计和运行时的 DataContext 属性的唯一方法是:

      if(( dependencyProperty == FrameworkElement.DataContextProperty
       ||  dependencyProperty == FrameworkContentElement.DataContextProperty)
      || (DesignerProperties.GetIsInDesignMode(dependencyObject)&&
       dataContextProp.Name.Equals("RuntimeDataContext") )))
      {
      
      }
      

      其中dependencyProperty 和dependencyObject 是以某种方式获得的引用,

      并且dependencyProperty 是在dependencyObject 引用的上下文中获得的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-31
        • 1970-01-01
        • 1970-01-01
        • 2019-02-28
        • 1970-01-01
        • 1970-01-01
        • 2017-08-03
        • 1970-01-01
        相关资源
        最近更新 更多