代码之家  ›  专栏  ›  技术社区  ›  Nicolas Dorier

wpf中的namescope是如何工作的?

  •  3
  • Nicolas Dorier  · 技术社区  · 17 年前

    我对wpf中的命名空间有一个奇怪的行为,我创建了一个名为fadingpupp的customcontrol,它是窗口的一个子类,里面没有什么特别的东西。

    <Window.Resources>
        <local:FadingPopup>
            <Button Name="prec" Content="ahah"></Button>
            <Button Content="{Binding ElementName=prec, Path=Content}"></Button>
        </local:FadingPopup>
    </Window.Resources>
    

    在这个片段中,绑定不起作用(总是空的)。如果我将这些按钮从资源移到窗口的内容,如下所示:

    <Window ...>
        <Button Name="prec" Content="ahah"></Button>
        <Button Content="{Binding ElementName=prec, Path=Content}"></Button>
    </Window>
    

    绑定按预期工作。

    现在,我试着把这两个片段混合起来:

    <Window...>
        <Window.Resources>
            <local:FadingPopup>
                <Button Name="prec" Content="Haha"></Button>
            </local:FadingPopup>
        </Window.Resources>
        <Button Content="{Binding ElementName=prec, Path=Content}"></Button>
    </Window>
    

    它也能工作。

    显然,如果按钮prec在资源中,它会在窗口的名称范围中注册自己。 但是,似乎绑定试图用fadingPopup的命名空间解析elementname(该命名空间为空),因此绑定不起作用…

    如果我在类FadingPopup中指定了一个名称作用域,那么我的第一个剪贴就可以正常工作:

    static FadingPopup()
    {
        NameScope.NameScopeProperty.OverrideMetadata(typeof(FadingPopup), new PropertyMetadata(new NameScope()));
    }
    

    但我不喜欢这个解决方案,因为我不明白为什么在第一个代码片段中,prec注册在窗口的名称范围中,而elementname是用fadinggroup的名称范围解析的(默认为空)。

    有人能给我解释一下发生了什么事吗?如果我没有为fadinggroup指定默认的名称范围,为什么我的第一个代码片段不起作用?

    1 回复  |  直到 14 年前
        1
  •  -2
  •   Muad'Dib    17 年前

    您应该检查控件上的数据上下文,执行类似的操作,然后就可以了。您可能需要添加路径,但可能不需要。

    <Window.Resources>
        <local:FadingPopup DataContext="{Binding}">
            <Button Name="prec" Content="ahah"></Button>
            <Button Content="{Binding ElementName=prec, Path=Content}"></Button>
        </local:FadingPopup>
    </Window.Resources>