我有这个模型(这不是实际代码,我省略了INotifyPropertyChanged实现以使它更清晰易懂)。
public class Project
{
public ObservableCollection<Component> Components { get; set; }
}
public class Component
{
public ObservableCollection<Item> Items { get; set; }
}
public class Item
{
public LookupItem LookupItem { get; set; }
}
这是ViewModel
public class ViewModel
{
public Project Project { get; set; }
public Components { get { return Project.Components; } }
public ObservableCollection<LookupItem> LookupItems { get; set; }
}
在我的视图中,我有两个列表视图,一个显示组件,另一个绑定到第一个,显示所选组件的项目。后面的列表视图应该为任何项目提供下拉框,以便更改查找项,但我无法进行绑定。
以下是XAML代码:
<ListView x:Name="list" ItemsSource="{Binding Components}">
......
</LIstView>
而后者
<ListView ItemsSource="{Binding Items}" DataContext="{Binding SelectedItem, ElementName=list}">
....
<GridViewColumn Width="140">
<GridViewColumnHeader Tag="Publisher" Content="Item" />
<GridViewColumn.CellTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch">
<ComboBox SelectedItem="{Binding Path=Item}" ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:ViewModel}}, Path=LookupItems, Mode=TwoWay }" DisplayMemberPath="Name" />
</Grid>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
我无法使下拉框填充。WPF给我错误提示。
System.Windows.Data Error: 4 : Cannot find source for binding with
reference 'RelativeSource FindAncestor, AncestorType='Projectname.ViewModels.ViewModel', AncestorLevel='1''. BindingExpression:Path=LookupItems; DataItem=null; target element is 'ComboBox' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')