2012-01-09 52 views
1

我有以下情況...我有一個包含ItemsControl的窗口。我爲Window的DataContext指定了一個ViewModel。我爲ItemControl的ItemTemplate指定了一個DataTemplate。在DataTemplate中,我使用ComboBox,對於ComboBox的ItemsSource,我使用RelativeSource綁定到其包含的Window的DataContext。在運行期間一切正常,並且Binding已正確解析,但在Design-Time Cider無法獲取包含Window的ViewModel的ItemSource綁定的視圖模型。從上面的代碼路徑= DataContext.AvailableGenres使用Wpf RelativeSource綁定中斷可混合性

<Window d:DataContext="{Binding Source={StaticResource DesignViewModel}}"> 

<Window.Resources> 
    <designviewmodels:GenresEditorDesignViewModel x:Key="DesignViewModel" /> 
</Window.Resources> 

<ItemsControl Grid.Row="0" Margin="3" ItemsSource="{Binding Path=CurrentState}" > 
<ItemsControl.ItemTemplate> 
    <DataTemplate> 
     <Grid DataContext="{Binding}"> 
      <Grid.ColumnDefinitions> 
       <ColumnDefinition Width="*"></ColumnDefinition> 
       <ColumnDefinition Width="20"></ColumnDefinition> 
      </Grid.ColumnDefinitions> 

      <ComboBox Grid.Column="0" Margin="3,0,3,0" 
       ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor, 
       AncestorType={x:Type Window}}, Path=DataContext.AvailableGenres, 
       Mode=OneWay}" 
       DisplayMemberPath="Name" 
       SelectedItem="{Binding Path=Genre, Mode=TwoWay}" DataContext=" 
       {Binding}" /> 

       </Grid> 
      </DataTemplate> 
     </ItemsControl.ItemTemplate> 
    </ItemsControl> 
</Window> 

所以基本上:

這裏是我的代碼(我離開了在頂部的XML命名空間的聲明,但在我的代碼,它們被包括在內)在設計時間內無法解析,但在運行時間內,它已正確解析。

有沒有人知道如果我做錯了什麼,或者它是Wpf xaml解析器的問題,它無法在設計時解析綁定到RelativeSources?

+0

...可混合性? – 2012-01-09 15:29:33

+0

創建設計時間數據的能力,以便設計師有 設計對... – Imri 2012-01-10 06:58:00

回答

1

我知道這是一個古老的問題,但爲了後人的緣故,我有一個適合我的解決方案。

我從來沒有能夠將RelativeSource綁定爲可混合的。但是,如果您有幸擁有沒有綁定的祖先,您可以在設計時環境中提供簽名帖子。

在備用祖先(在這種情況下,網格)將DataContext綁定到相同的RelativeSource ,但的Path設置爲僅DataContext。然後,將d:DataContext應用於相同的祖先,併爲其提供您想要綁定到您的實際原始元素上的類型(或等效模擬)。最後,按照常規方式將原始元素(ComboBox)綁定到屬性或路徑。

<Grid 
    DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, 
      AncestorType={x:Type Window}}, Path=DataContext, 
      Mode=OneWay}" 
    d:DataContext="{Binding Source={StaticResource DesignViewModel}}" > 
     <Grid.ColumnDefinitions> 
      <ColumnDefinition Width="*"></ColumnDefinition> 
      <ColumnDefinition Width="20"></ColumnDefinition> 
     </Grid.ColumnDefinitions> 

     <ComboBox Grid.Column="0" Margin="3,0,3,0" 
      ItemsSource="{Binding Path=AvailableGenres, Mode=OneWay}" 
      DisplayMemberPath="Name" 
      SelectedItem="{Binding Path=Genre, Mode=TwoWay}" DataContext=" 
      {Binding}" /> 

</Grid>