数据绑定到DataTemplate中的ListView项

时间:2016-05-12 01:12:17

标签: wpf xaml listview data-binding datatemplate

我有一个用户控件(WaypointInfoControl),我写了一个名为TheGraphic的依赖属性,如下所示:

public Graphic TheGraphic
{
    get { return (Graphic)GetValue(TheGraphicProperty); }
    set { SetValue(TheGraphicProperty, value); }
}

public static readonly DependencyProperty TheGraphicProperty =
    DependencyProperty.Register("TheGraphic", typeof(Graphic), typeof(WaypointInfoControl), new PropertyMetadata(default(Graphic)));

我有一个viewmodel,其Waypoints属性定义如下:

private ObservableCollection<Graphic>_Waypoints = new GraphicCollection();
public ObservableCollection<Graphic> Waypoints
{
    get { return _Waypoints; }
    set { RaiseAndSetIfChanged(ref _Waypoints, value); }
}

在我的xaml中,我有一个ListView,我想用Waypoints填充:

<ListView ItemsSource="{Binding Waypoints}"  >
   <ListView.ItemTemplate >
       <DataTemplate >
            <controld:WaypointInfoControl TheGraphic="????"   />
       </DataTemplate>
   </ListView.ItemTemplate>
</ListView>

如何将TheGraphic绑定到它所代表的ListView中的单个项目?

1 个答案:

答案 0 :(得分:3)

您的ItemsSource绑定了Graphic个对象的集合,这意味着DataContext中每个项目的ListView将是一个Graphic个对象。由于您要绑定的DependencyProperty正在寻找您只想绑定到整个Graphic的{​​{1}}对象,因此您可以通过使用绑定标记扩展来实现此目的,而无需指定一个路径(这只会导致绑定拉入整个DataContext,在你的情况下是你正在寻找的Graphic对象。)

所以这应该有效:

DataContext