gpt4 book ai didi

c# - Wpf 主从 ListView 绑定(bind)

转载 作者:行者123 更新时间:2023-11-30 16:13:10 29 4
gpt4 key购买 nike

我有一个这个模型(它不是实际代码,为了清楚起见,我省略了 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; }
}

这是 View 模型

  public class ViewModel
{
public Project Project { get; set; }
public Components { get { return Project.Components; } }

public ObservableCollection<LookupItem> LookupItems { get; set; }
}

在 View 中,我有两个 ListView ,一个显示组件,另一个绑定(bind)到第一个显示所选组件项目的 ListView 。后一个 ListView 应该有一个用于任何项目的组合框,以便更改 lookupitem,但我无法绑定(bind)它。

这是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')

最佳答案

尝试将您的 ViewModel 添加为 DataContext,例如。对于 Window,像这样:

<Window.DataContext>
<local:ViewModel />
</Window.DataContext>

或在代码隐藏中:

var viewModel = new ViewModel();
this.DataContext = viewModel;

然后在 DataTemplate 中这样写:

<DataTemplate>
<Grid HorizontalAlignment="Stretch">
<ComboBox ItemsSource="{Binding Path=DataContext.LookupItems,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}},
Mode=TwoWay}" ... />
</Grid>
</DataTemplate>

关于c# - Wpf 主从 ListView 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22113864/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com