加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何在自定义MarkupExtension中处理Freezable?

发布时间:2020-12-15 17:23:15 所属栏目:百科 来源:网络整理
导读:我有一个工作 custom markup extension,它以特定的方式从DataContext中检索信息(这个问题并不重要). 一切都很好,直到我在不属于视觉或逻辑树的元素中使用此标记扩展.在我的元素InputBindings中的特定示例中.在这种情况下,我没有将FrameworkElement检索为Depe
我有一个工作 custom markup extension,它以特定的方式从DataContext中检索信息(这个问题并不重要).

一切都很好,直到我在不属于视觉或逻辑树的元素中使用此标记扩展.在我的元素InputBindings中的特定示例中.在这种情况下,我没有将FrameworkElement检索为DependencyObject,而是获得Freezable(KeyBinding).

如何通过代码访问DataContext?

我的XAML代码:

<UserControl.InputBindings>
    <KeyBinding
        Key="CapsLock"
        Command="{wtc:CommandBinding {x:Static b:Commands.OpenTimeLine}}" />
</UserControl.InputBindings>

我的自定义标记扩展中的代码,我通常检索我的DataContext:

protected override object ProvideValue(
    DependencyObject dependencyObject,DependencyProperty dependencyProperty )
{
    if ( dependencyObject is Freezable )
    {
        // TODO: How to handle freezable?
    }

    _frameworkElement = dependencyObject as FrameworkElement;
    if ( _frameworkElement == null )
    {
        throw new InvalidImplementationException(
            "The DataContextBinding may only be used on framework elements." );
    }

    if ( !_dataContextChangedHooked )
    {
        _frameworkElement.DataContextChanged += DataContextChanged;
        _dataContextChangedHooked = true;
    }

    return ProvideValue( _frameworkElement.DataContext );
}

整个源代码也在线.我有很多用于标记扩展的类层次结构.

AbstractMarkupExtension?AbstractDependencyPropertyBindingExtension?AbstractDataContextBindingExtension?CommandBindingExtension

解决方法

一种解决方案非常容易.假设您要查找的DataContext与根对象的DataContext相同,则只需使用 IRootObjectProvider.此提供程序可通过IServiceProvider访问,该提供程序作为ProvideValue的参数传递.

var rootProvider = (IRootObjectProvider)ServiceProvider
                       .GetService( typeof( IRootObjectProvider ) );
_frameworkElement = rootProvider.RootObject as FrameworkElement;

可能存在更复杂的场景,您必须遍历树(通过LogicalChildren)才能找到所需的DataContext.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读