在窗口上直接绑定AttachedProperty
问题描述:
Question:使用XAML,如何在值为复数值时直接在窗口上设置附加属性?在窗口上直接绑定AttachedProperty
说明:
请注意,我已经删除了一些XAML代码在这里和那里为简洁起见。
我想直接在WPF窗口上设置附加属性。通常情况下,它可以被设置为像这样的窗口的属性:
<Window
xmlns:data="clr-namespace:MVVM_Test.Data"
data:AttachedProperties.RegisterCommandBindings="somevalue" />
这是细如果属性只需要一个简单的值(或甚至简单的结合)。但是,我想使用MultiBinding将附加属性设置为复杂值。我有这样的工作,当我做出附加属性我网中的一员:
<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上设置它。
如果我把附加属性结合作为窗口的第一个成员,Window.Resources之前,我从窗口的XAML声明运行时异常:
System.Windows.StaticResourceExtension“上提供价值” '抛出了一个例外。'行号“6”和行位置“9”。
与内部异常:
找不到资源名为 'RegisterCommandBindingsConverter'。资源名称区分大小写。
如果我把Window.Resources后,但仍作为窗口的直接成员和网格之前附加属性的结合,我得到以下错误在编译时:
对象“窗口”已经有一个孩子,不能添加''。 “窗口”只能接受一个孩子。 Line 42 Position 11.
答
你想要做的错事就是你不能在窗口资源中使用任何项目(在这种情况下转换器)在同一个窗口中定义。您必须在外部资源字典中定义转换器,如App.xaml
的ResourcesDictionary
。看看这个代码:
<Application x:Class="WpfApplication3.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<data:BindingConverter x:Key="RegisterCommandBindingsConverter" />
</Application.Resources>
试试这个,我觉得应该工作。希望有所帮助...