2

次のシナリオがあります... ItemsControl を含むウィンドウがあります。Window の DataContext に ViewModel を指定します。ItemControl の ItemTemplate に DataTemplate を指定します。DataTemplate では ComboBox を使用し、ComboBox の ItemsSource では、それを含む Window の DataContext への RelativeSource Binding を使用します。ランタイム中はすべて正常に動作し、Binding は正しく解決されますが、デザインタイム中、Cider は ItemSource がバインドされているウィンドウのビューモデルを取得できません。

これが私のコードです(上部のxml名前空間宣言を省略しましたが、私のコードには含まれています):

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

したがって、基本的に上記のコードから、Path=DataContext.AvailableGenres は設計時には解決できませんが、実行時には正しく解決されます。

私が何か間違ったことをしているのか、それとも設計時に RelativeSources へのバインディングを解決できないという Wpf xaml パーサーの問題なのか、誰かが知っていますか?

4

1 に答える 1

1

これは古い質問であることは知っていますが、後世のために、自分に合った解決策があります。

RelativeSource バインディングを Blendable にすることはできませんでした。ただし、幸運にも祖先に対してバインドが設定されていない先祖を持つことができる場合は、設計時環境に道しるべを提供できます。

予備の祖先 (この場合はグリッド) で、DataContext を同じ RelativeSource にバインドします。ただし、Path を DataContext のみに設定します。次に、同じ祖先に ad: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>
于 2013-06-06T03:45:49.800 に答える