Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将SelectedItem绑定到WPF中的正确数据上下文_C#_Wpf_Xaml_Mvvm - Fatal编程技术网

C# 将SelectedItem绑定到WPF中的正确数据上下文

C# 将SelectedItem绑定到WPF中的正确数据上下文,c#,wpf,xaml,mvvm,C#,Wpf,Xaml,Mvvm,我有一个UserControlbarView和相应的ViewModelbarViewModel。此ViewModel具有属性SelectedSomething,该属性绑定到我的视图中的不同列表框 如果我有这样的结构,那么一切都很好: <UserControl DataContext="barViewModel"> <ListBox ItemsSource="{Binding ObservableCollectionWithItems}" Sel

我有一个UserControl
barView
和相应的ViewModel
barViewModel
。此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}}"