[英]Wpf master detail listview binding
I have a this model (it's not the actual code, I omitted the INotifyPropertyChanged implementation for clarity). 我有一个这个模型(它不是实际的代码,为了清楚起见我省略了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; }
}
And this is the ViewModel 这就是ViewModel
public class ViewModel
{
public Project Project { get; set; }
public Components { get { return Project.Components; } }
public ObservableCollection<LookupItem> LookupItems { get; set; }
}
In the view I have two listviews one showing the Components and the other binded to the first one showing the Items of the selecte Component. 在视图中,我有两个列表视图,一个显示组件,另一个绑定到第一个显示选择组件的项目。 The latter listview should have a combobox for any Item in order to change the lookupitem, but I cannot bind it. 后面的listview应该有一个任何Item的组合框,以便更改lookupitem,但我无法绑定它。
This is the xaml 这是xaml
<ListView x:Name="list" ItemsSource="{Binding Components}">
......
</LIstView>
and the latter 而后者
<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>
I cannot make the combobox populate. 我不能让组合框填充。 Wpf gives me the error 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')
Try adding your ViewModel
as DataContext, eg. 尝试将ViewModel
添加为DataContext,例如。 for Window
, like this: 对于Window
,像这样:
<Window.DataContext>
<local:ViewModel />
</Window.DataContext>
or in code-behind: 或在代码隐藏中:
var viewModel = new ViewModel();
this.DataContext = viewModel;
And in DataTemplate write this: 在DataTemplate中写下这个:
<DataTemplate>
<Grid HorizontalAlignment="Stretch">
<ComboBox ItemsSource="{Binding Path=DataContext.LookupItems,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}},
Mode=TwoWay}" ... />
</Grid>
</DataTemplate>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.