2012-03-27 43 views
1

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.

回答

2

你想要做的錯事就是你不能在窗口資源中使用任何項目(在這種情況下轉換器)在同一個窗口中定義。您必須在外部資源字典中定義轉換器,如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> 

試試這個,我覺得應該工作。希望有所幫助...