【问题标题】:Bind SelectedItem to correct DataContext in WPF将 SelectedItem 绑定到 WPF 中的正确 DataContext
【发布时间】:2016-09-13 07:40:33
【问题描述】:

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

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

<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 对象的 observalbe 集合。新视图如下所示:

<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 错误:40:BindingExpression 路径错误:在“对象”“ItemsGroup”(HashCode=10335672)上找不到“SelectedSomething”属性。 BindingExpression:Path=SelectedSomething; DataItem='ItemsGroup' (HashCode=10335672);目标元素是 'ListBox' (Name='');目标属性是“SelectedItem”(类型“对象”)

我尝试将 SelectedItem 更改为:

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

这将消除错误,但我的SelectedSomething 仍未绑定到列表框。我该如何解决这个问题?

【问题讨论】:

    标签: c# wpf xaml mvvm


    【解决方案1】:

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

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

    另请注意,不必在SelectedItem 绑定上设置Mode=TwoWay,因为该属性默认为双向绑定。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 2010-10-24
      • 2011-01-02
      • 2013-11-16
      相关资源
      最近更新 更多