【问题标题】:Binding an AttachedProperty directly on a Window直接在窗口上绑定 AttachedProperty
【发布时间】:2013-03-22 04:30:54
【问题描述】:

问题:使用 XAML,当值是复杂值时,如何直接在 Window 上设置 Attached Property?

说明:

请注意,为简洁起见,我已在各处删除了一些 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 上,而不是 Grid 上。虽然 Grid 上的 Attached 属性完全符合我的需要,但让我感到困扰的是,我无法弄清楚如何在 Window 上设置它。

如果我将 Attached Property 绑定作为 Window 的第一个成员,在 Window.Resources 之前,我会从 Window 的 XAML 中得到一个运行时异常,说明:

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

内部例外:

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

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

对象 'Window' 已经有一个子对象,不能添加 ''。 'Window' 只能接受一个孩子。第 42 行第 11 行。

【问题讨论】:

    标签: wpf xaml data-binding attached-properties


    【解决方案1】:

    您想要做的错误是您不能在同一个窗口中使用窗口资源中定义的任何项目(在这种情况下为转换器)。您必须在外部资源字典中定义转换器,例如App.xamlResourcesDictionary。看看这段代码:

    <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>
    

    试试这个,我认为应该可以。希望有帮助...

    【讨论】:

      猜你喜欢
      • 2016-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-10
      相关资源
      最近更新 更多