数据绑定到 DataTemplate 中的 ListView 项
Databinding to ListView Item in 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)));
我有一个视图模型 Waypoints 属性 定义如下:
private ObservableCollection<Graphic>_Waypoints = new GraphicCollection();
public ObservableCollection<Graphic> Waypoints
{
get { return _Waypoints; }
set { RaiseAndSetIfChanged(ref _Waypoints, value); }
}
在我的 xaml 中,我有一个要用 Waypoints:
填充的 ListView
<ListView ItemsSource="{Binding Waypoints}" >
<ListView.ItemTemplate >
<DataTemplate >
<controld:WaypointInfoControl TheGraphic="????" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
如何将 TheGraphic 绑定到它所代表的 ListView 中的单个项目?
您的 ItemsSource
绑定到 Graphic
对象的集合,这意味着 ListView
中每个项目的 DataContext
将是一个 Graphic
目的。由于您要绑定到的 DependencyProperty
正在寻找您只想绑定到整个 DataContext
的 Graphic
对象,您可以通过使用绑定标记扩展而不指定一条路径(这只会导致绑定拉入整个 DataContext
,在您的情况下,这就是您正在寻找的 Graphic 对象)。
所以这应该有效:
<ListView ItemsSource="{Binding Waypoints}" >
<ListView.ItemTemplate >
<DataTemplate >
<controld:WaypointInfoControl TheGraphic="{Binding}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
我有一个我编写的用户控件 (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)));
我有一个视图模型 Waypoints 属性 定义如下:
private ObservableCollection<Graphic>_Waypoints = new GraphicCollection();
public ObservableCollection<Graphic> Waypoints
{
get { return _Waypoints; }
set { RaiseAndSetIfChanged(ref _Waypoints, value); }
}
在我的 xaml 中,我有一个要用 Waypoints:
填充的 ListView<ListView ItemsSource="{Binding Waypoints}" >
<ListView.ItemTemplate >
<DataTemplate >
<controld:WaypointInfoControl TheGraphic="????" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
如何将 TheGraphic 绑定到它所代表的 ListView 中的单个项目?
您的 ItemsSource
绑定到 Graphic
对象的集合,这意味着 ListView
中每个项目的 DataContext
将是一个 Graphic
目的。由于您要绑定到的 DependencyProperty
正在寻找您只想绑定到整个 DataContext
的 Graphic
对象,您可以通过使用绑定标记扩展而不指定一条路径(这只会导致绑定拉入整个 DataContext
,在您的情况下,这就是您正在寻找的 Graphic 对象)。
所以这应该有效:
<ListView ItemsSource="{Binding Waypoints}" >
<ListView.ItemTemplate >
<DataTemplate >
<controld:WaypointInfoControl TheGraphic="{Binding}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>