直接在窗口上绑定附加属性

时间:2012-03-27 20:06:51

标签: wpf xaml data-binding attached-properties

问题:使用XAML,当值是复数值时,如何直接在窗口上设置附加属性?

解释

请注意,为了简洁起见,我已经删除了一些XAML代码。

我正在尝试直接在WPF窗口上设置附加属性。通常,它可以设置为窗口的属性,如下所示:

<Window 
xmlns:data="clr-namespace:MVVM_Test.Data"
data:AttachedProperties.RegisterCommandBindings="somevalue" />

如果属性只需要一个简单的值(甚至是简单的绑定),这很好。但是,我想使用MultiBinding将附加属性设置为复杂值。当我将Attached Property作为我的Grid的成员时,我有这个工作:

<Window>
    <Window.Resources>
        <data:BindingConverter x:Key="RegisterCommandBindingsConverter" />
    </Window.Resources>
    <Grid>
        <data:AttachedProperties.RegisterCommandBindings>
            <MultiBinding Converter="{StaticResource RegisterCommandBindingsConverter}">
                <Binding RelativeSource="{RelativeSource Mode=Self}" Path="(data:AttachedProperties.BaseBindings)" />
                <Binding ElementName="automobileView"  Path="DataContext.CommandBindings" />
            </MultiBinding>
        </data:AttachedProperties.RegisterCommandBindings>

但是,我希望附加属性驻留在Window上,而不是Grid上。虽然在Grid上使用Attached属性正是我所需要的,但是我无法弄清楚如何在Window上设置它。

如果我把附加属性绑定作为Window的第一个成员,在Window.Resources之前,我从Window的XAML得到一个运行时异常,说明:

  

'在'System.Windows.StaticResourceExtension'上提供值引发异常。行号“6”和行位置“9”。

内部例外:

  

找不到名为“RegisterCommandBindingsConverter”的资源。资源名称区分大小写。

如果我将Window.Resources之后的附加属性绑定但仍作为Window的直接成员并在Grid之前,我在编译时遇到以下错误:

  

对象'Window'已经有一个孩子,无法添加''。 '窗口'只能接受一个孩子。第42行第11位。

1 个答案:

答案 0 :(得分:2)

您想要做的事情的错误在于您不能在同一窗口中使用窗口资源中定义的任何项目(在本例中为转换器)。您必须在外部资源字典中定义转换器,例如App.xaml的{​​{1}}。看看这段代码:

ResourcesDictionary

试试这个,我觉得应该有效。希望有帮助...