Wpf 在嵌套的Listview中绑定选定项时出现问题
目前,我使用嵌套在listview中的listview以图形方式显示淘汰赛样式的比赛,该比赛由SectionTreeOne在ViewModel中备份,其中包含对象列表“TournamentNode”。然而,当我点击它时,我无法让我选择的“锦标赛节点”绑定Wpf 在嵌套的Listview中绑定选定项时出现问题,wpf,xaml,mvvm,windows-8,windows-store-apps,Wpf,Xaml,Mvvm,Windows 8,Windows Store Apps,目前,我使用嵌套在listview中的listview以图形方式显示淘汰赛样式的比赛,该比赛由SectionTreeOne在ViewModel中备份,其中包含对象列表“TournamentNode”。然而,当我点击它时,我无法让我选择的“锦标赛节点”绑定 <Grid Grid.Row="2"> <ListView ItemsSource="{Binding SectionTreeOne}">
<Grid Grid.Row="2">
<ListView ItemsSource="{Binding SectionTreeOne}">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate >
<DataTemplate>
<ListView ItemsSource="{Binding}" SelectionMode="Single"
SelectedItem="{Binding SelectedTournamentNode}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
尝试以下绑定:
SelectedItem="{Binding SelectedTournamentNode, Mode=TwoWay}"
请记住,WinRT始终使用单向绑定模式作为默认模式,这与WPF中的情况不同,后者根据属性性质或可访问性自动选择绑定模式
我在WinRT中使用的避免此类错误的一个好原则是始终明确指定绑定模式
所以我终于找出了你装订的错误。首先,如上所述,
SelectedItem
绑定模式必须明确设置为TwoWay
其次,嵌套列表绑定到SectionTreeOne
列表中的一个内部列表,因此,如果要将SelectedItem
绑定到视图模型上的属性,必须使用命名元素将该属性重新绑定到父列表的DataContext
。实际上,您试图绑定到内部列表上的不存在属性,而不是绑定到属性所在的视图模型
<ListView x:Name="listView" ItemsSource="{Binding SectionTreeOne}">
...
<ListView.ItemTemplate >
<DataTemplate>
<ListView ItemsSource="{Binding}" SelectionMode="Single"
SelectedItem="{Binding Path=DataContext.SelectedTournamentNode, ElementName=listView, Mode=TwoWay}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
...
请阅读Visual Studio调试器输出,它提供了关于绑定链中可能发生的绑定错误的非常有用的信息,特别是如果您绑定嵌套在另一个列表中的列表,它将为您省去很多麻烦 不幸的是,这并没有奏效。我不确定为什么,因为这似乎是一个相当直接的绑定。我已经为非嵌套的ListView实现并使用了此选项,但对于嵌套的ListView,选择似乎根本不起作用。是否检查了调试器控制台以查看是否存在任何绑定错误?是的,viewmodel中的SelectedItem属性根本未被访问。我已将C#添加到上述帖子中。我开始认为我无法选择该项目,因为它不是一个可观察的集合。您认为可能是这样吗?ItemsControl(如ListView)接受绑定到实现
IEnumerable
接口的任何集合,因此在您绑定到列表时,这不会成为问题ObservableCollection
只是一个集合,每当您使用集合的Add
、Remove
和Clear
(此方法不确定)方法时,它都会通知接口。因此,当集合发生变化时,您不必担心自己提高OnPropertyChanged
。好的,这都是关于培训和练习的,尤其是使用MVVM。绑定并不难理解,但完全理解它的功能非常重要,因为它是XAML和MVVM之间的粘合剂。了解绑定模式和调试,并小心处理WPF的文档,因为在Windows 8中有相当多的属性和bevahior被禁止!关于MVVM,尽管我读过关于这个主题的好书,但我只是通过实践来学习,因为这是充分理解其内在概念的唯一途径。首先避免使用框架!
SelectedItem="{Binding SelectedTournamentNode, Mode=TwoWay}"
<ListView x:Name="listView" ItemsSource="{Binding SectionTreeOne}">
...
<ListView.ItemTemplate >
<DataTemplate>
<ListView ItemsSource="{Binding}" SelectionMode="Single"
SelectedItem="{Binding Path=DataContext.SelectedTournamentNode, ElementName=listView, Mode=TwoWay}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>