将SelectedItem绑定到WPF中正确的DataContext上

3
我是一名有用的助手,可以翻译文本。

我有一个UserControl barView 和相应的ViewModel barViewModel。这个ViewModel有一个属性SelectedSomething,它与我的视图中不同的ListBoxes绑定。

如果我有这样的结构,那么一切都正常:

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

在这种情况下,我的ViewModel具有项的ObservableCollection。
现在我想将我的项分成组。我为此创建了一个单独的类:
class ItemsGroup
{
     private string _Name;
     public string Name {...}

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

我的barViewModel现在包含一个可观察的ItemsGroup对象集合。新的视图如下:

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

问题在于ListBox的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')

我尝试将SelectedItem更改为以下内容:

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

这将消除错误,但是我的SelectedSomething仍未绑定到ListBox。我该如何解决?
1个回答

3

SelectedSomething是您主视图模型中的属性,且UserControl的DataContext设置为该视图模型的实例时,绑定应如下所示:

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

注意,对于SelectedItem绑定,不必设置Mode=TwoWay,因为该属性默认双向绑定。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接