私は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 {...}
}
マイbarViewModel
今ItemsGroup
オブジェクトの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
がそのビューモデルのインスタンスに設定されている場合