2016-09-13 6 views
2

私はUserControl barViewと対応するViewModel barViewModelを持っています。このViewModelのプロパティはSelectedSomethingで、私のビュー内の異なるListBoxにバインドされています。WPFでDataContextを修正するためにSelectedItemをバインドします

私はこのような建設、その後、すべての中華鍋罰金がある場合:この場合

<UserControl DataContext="barViewModel"> 
    <ListBox ItemsSource="{Binding ObservableCollectionWithItems}" 
      SelectedItem="{Binding SelectedSomething, Mode=TwoWay}"> 
     .... 
    </ListBox> 
</UserControl> 

を私のViewModelには、アイテムとのObservableCollectionを持っています。

今、アイテムをグループに分割したいと考えています。私はそのためsepareteクラスを作成します。

class ItemsGroup 
{ 
    private string _Name; 
    public string Name {...} 

    private List<Item> _ItemsList; 
    public List<Item> ItemsList {...} 
} 

マイbarViewModelItemsGroupオブジェクトのobservalbeコレクションが含まれています。このための新しいビューは次のようになります。私はへのSelectedItemを変更しようとしました

System.Windows.Data Error: 40 : BindingExpression path error: 'SelectedSomething' property not found on 'object' ''ItemsGroup' (HashCode=10335672)'. BindingExpression:Path=SelectedSomething; DataItem='ItemsGroup' (HashCode=10335672); target element is 'ListBox' (Name=''); target property is 'SelectedItem' (type 'Object')

<UserControl DataContext="barViewModel"> 
<ItemsControl ItemsSource="{Binding ObservalbeCollectionWithItemsGroup}"> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate DataType="{x:Type test:ItemsGroup}"> 
      <Expander IsExpanded="False"> 
       <Expander.Header> 
        <TextBlock Content="{Binding Name}"/> 
       </Expander.Header> 
       <ListBox ItemsSource="{Binding ItemsList}" Margin="10" 
         SelectedItem="{Binding SelectedSomething, Mode=TwoWay}"> 
        ... 
       </ListBox> 
      </Expander> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

問題は、リストボックスのSelectedItemのが親にバインドさと私は、このエラーが表示されていることですこの:

Text="{Binding SelectedSomething, 
       RelativeSource={RelativeSource Mode=FindAncestor, 
               AncestorType={x:Type UserControl}}}" 

これはエラーを削除しますが、SelectedSomethingはstiですListBoxにバインドされません。これをどうすれば解決できますか?それはだということも

SelectedItem="{Binding DataContext.SelectedSomething, 
       RelativeSource={RelativeSource AncestorType=UserControl}}" 

注:SelectedSomethingは、あなたのメインビューモデルのプロパティであり、そしてUserControlのDataContextがそのビューモデルのインスタンスに設定されている場合

答えて

2

は、結合は次のようになります。プロパティがデフォルトで双方向をバインドするため、Mode=TwoWaySelectedItemバインディングに設定する必要はありません。

関連する問題