C# 将SelectedItem绑定到WPF中的正确数据上下文
我有一个UserControlC# 将SelectedItem绑定到WPF中的正确数据上下文,c#,wpf,xaml,mvvm,C#,Wpf,Xaml,Mvvm,我有一个UserControlbarView和相应的ViewModelbarViewModel。此ViewModel具有属性SelectedSomething,该属性绑定到我的视图中的不同列表框 如果我有这样的结构,那么一切都很好: <UserControl DataContext="barViewModel"> <ListBox ItemsSource="{Binding ObservableCollectionWithItems}" Sel
barView
和相应的ViewModelbarViewModel
。此ViewModel具有属性SelectedSomething
,该属性绑定到我的视图中的不同列表框
如果我有这样的结构,那么一切都很好:
<UserControl DataContext="barViewModel">
<ListBox ItemsSource="{Binding ObservableCollectionWithItems}"
SelectedItem="{Binding SelectedSomething, Mode=TwoWay}">
....
</ListBox>
</UserControl>
问题是ListBox的SelectedItem绑定到父项,并显示此错误:
System.Windows.Data错误:40:BindingExpression路径错误:“在“对象”“项组”(HashCode=10335672)上找不到SelectedSomething”属性。BindingExpression:Path=SelectedSomething;DataItem='ItemsGroup'(HashCode=10335672);目标元素是'ListBox'(名称='');目标属性为“SelectedItem”(类型为“Object”)
我尝试将SelectedItem更改为:
Text="{Binding SelectedSomething,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type UserControl}}}"
这将删除错误,但我的
SelectedSomething
仍未绑定到列表框。如何修复此问题?当主视图模型中的属性是SelectedSomething
,并且UserControl的DataContext
设置为该视图模型的实例时,绑定应如下所示:
<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="{Binding DataContext.SelectedSomething,
RelativeSource={RelativeSource AncestorType=UserControl}}"
还请注意,没有必要在
SelectedItem
绑定上设置Mode=TwoWay
,因为默认情况下该属性是双向绑定的
SelectedItem="{Binding DataContext.SelectedSomething,
RelativeSource={RelativeSource AncestorType=UserControl}}"